diff --git a/v3/@claude-flow/cli/__tests__/plugins-trust-3557.test.ts b/v3/@claude-flow/cli/__tests__/plugins-trust-3557.test.ts new file mode 100644 index 0000000000..bd5ff36850 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/plugins-trust-3557.test.ts @@ -0,0 +1,209 @@ +/** + * #3557 — `plugins install --verify` must enforce declared trust/permissions + * and registry checksums instead of being parsed and ignored. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { createHash } from 'crypto'; + +// Every npm call goes through child_process.execFile. The mock records calls +// and fakes `npm pack` by writing a tarball whose bytes the test controls. +const npmCalls: string[][] = []; +let packBytes = Buffer.from('tarball-bytes'); +vi.mock('child_process', () => ({ + execFile: (file: string, args: string[], _opts: unknown, cb: (e: unknown, r?: unknown) => void) => { + const npmArgs = file === 'cmd.exe' ? args.slice(4) : args; + npmCalls.push(npmArgs); + if (npmArgs[0] === 'pack') { + const dest = npmArgs[npmArgs.indexOf('--pack-destination') + 1]; + fs.writeFileSync(path.join(dest, 'evil-plugin-1.0.0.tgz'), packBytes); + cb(null, { stdout: JSON.stringify([{ filename: 'evil-plugin-1.0.0.tgz' }]), stderr: '' }); + return; + } + cb(null, { stdout: '', stderr: '' }); + }, +})); + +import { PluginManager } from '../src/plugins/manager.js'; +import { + DEFAULT_PLUGIN_PERMISSIONS, + evaluatePluginTrust, + parseSha256Checksum, + readDeclaredTrust, +} from '../src/plugins/trust-policy.js'; + +function makeLocalPlugin(root: string, name: string, extra: Record): string { + const dir = path.join(root, name); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync( + path.join(dir, 'package.json'), + JSON.stringify({ + name, + version: '1.0.0', + 'claude-flow': { hooks: ['pre-task'], commands: ['probe'], ...extra }, + }), + ); + return dir; +} + +function readManifest(base: string): Record { + const p = path.join(base, '.claude-flow', 'plugins', 'installed.json'); + if (!fs.existsSync(p)) return { plugins: {} }; + return JSON.parse(fs.readFileSync(p, 'utf-8')); +} + +describe('#3557 plugin install trust enforcement', () => { + let base: string; + let manager: PluginManager; + + beforeEach(async () => { + base = fs.mkdtempSync(path.join(os.tmpdir(), 'plugins-trust-3557-')); + manager = new PluginManager(base); + await manager.initialize(); + npmCalls.length = 0; + packBytes = Buffer.from('tarball-bytes'); + }); + + afterEach(() => { + fs.rmSync(base, { recursive: true, force: true }); + }); + + it("Martin's repro: an untrusted local plugin with elevated permissions registers no hooks by default, and the manifest records trust + permissions", async () => { + const dir = makeLocalPlugin(base, 'evil-probe', { + trustLevel: 'untrusted', + permissions: ['filesystem:write', 'network:all', 'shell:exec', 'secrets:read'], + }); + + const result = await manager.installFromLocal(dir, { verify: true }); + + expect(result.success).toBe(true); + expect(result.plugin!.hooks).toEqual([]); + expect(result.plugin!.commands).toEqual([]); + + const entry = readManifest(base).plugins['evil-probe']; + expect(entry.trustLevel).toBe('untrusted'); + expect(entry.permissions).toEqual(['filesystem:write', 'network:all', 'shell:exec', 'secrets:read']); + expect(entry.hooks).toEqual([]); + expect(entry.withheld.hooks).toEqual(['pre-task']); + expect(entry.withheld.commands).toEqual(['probe']); + expect(entry.withheld.reasons.join(' ')).toMatch(/untrusted/); + expect(entry.withheld.reasons.join(' ')).toMatch(/shell:exec/); + }); + + it('with no options at all, a local install still enforces (secure default)', async () => { + const dir = makeLocalPlugin(base, 'evil-default', { trustLevel: 'untrusted', permissions: ['shell:exec'] }); + const result = await manager.installFromLocal(dir); + expect(result.plugin!.hooks).toEqual([]); + }); + + it('--trust registers the hooks and commands of the same plugin', async () => { + const dir = makeLocalPlugin(base, 'evil-trusted', { + trustLevel: 'untrusted', + permissions: ['filesystem:write', 'network:all', 'shell:exec', 'secrets:read'], + }); + + const result = await manager.installFromLocal(dir, { verify: true, trust: true }); + + expect(result.success).toBe(true); + const entry = readManifest(base).plugins['evil-trusted']; + expect(entry.hooks).toEqual(['pre-task']); + expect(entry.commands).toEqual(['probe']); + expect(entry.trustLevel).toBe('untrusted'); + expect(entry.withheld).toBeUndefined(); + }); + + it('a benign plugin (default permission set only) installs as before, with trust recorded', async () => { + const dir = makeLocalPlugin(base, 'benign', { trustLevel: 'community', permissions: [...DEFAULT_PLUGIN_PERMISSIONS] }); + + const result = await manager.installFromLocal(dir, { verify: true }); + + expect(result.success).toBe(true); + const entry = readManifest(base).plugins['benign']; + expect(entry.hooks).toEqual(['pre-task']); + expect(entry.commands).toEqual(['probe']); + expect(entry.permissions).toEqual(['memory:read']); + expect(entry.trustLevel).toBe('community'); + expect(entry.verification).toBe('policy'); + expect(entry.withheld).toBeUndefined(); + }); + + it('--no-verify keeps the old behaviour but marks verification as skipped', async () => { + const dir = makeLocalPlugin(base, 'evil-noverify', { trustLevel: 'untrusted', permissions: ['shell:exec'] }); + + const result = await manager.installFromLocal(dir, { verify: false }); + + expect(result.decision!.verificationSkipped).toBe(true); + const entry = readManifest(base).plugins['evil-noverify']; + expect(entry.hooks).toEqual(['pre-task']); + expect(entry.verification).toBe('skipped'); + expect(entry.permissions).toEqual(['shell:exec']); + }); + + it('a registry checksum mismatch fails closed: nothing is installed and nothing is recorded', async () => { + const expected = createHash('sha256').update('the-bytes-the-registry-published').digest('hex'); + packBytes = Buffer.from('tampered-bytes'); + + const result = await manager.installFromNpm('evil-plugin', undefined, { + verify: true, + expectedChecksum: `sha256:${expected}`, + }); + + expect(result.success).toBe(false); + expect(result.error).toMatch(/Checksum mismatch/); + expect(npmCalls.some((a) => a[0] === 'install')).toBe(false); + expect(readManifest(base).plugins['evil-plugin']).toBeUndefined(); + }); + + it('a matching registry checksum installs from the exact tarball that was hashed', async () => { + const expected = createHash('sha256').update(packBytes).digest('hex'); + + const result = await manager.installFromNpm('evil-plugin', undefined, { + verify: true, + expectedChecksum: `sha256:${expected}`, + registryTrustLevel: 'official', + }); + + expect(result.success).toBe(true); + const install = npmCalls.find((a) => a[0] === 'install')!; + expect(install[install.length - 1]).toMatch(/evil-plugin-1\.0\.0\.tgz$/); + expect(result.plugin!.verification).toBe('checksum'); + }); + + it('a placeholder registry checksum is not treated as verified; it warns and falls back to npm integrity', async () => { + const result = await manager.installFromNpm('evil-plugin', undefined, { + verify: true, + expectedChecksum: 'sha256:abc123neural', + }); + + expect(result.success).toBe(true); + expect(result.plugin!.verification).toBe('npm-integrity'); + expect(result.warnings!.join(' ')).toMatch(/not a verifiable sha256/); + expect(npmCalls.some((a) => a[0] === 'pack')).toBe(false); + }); +}); + +describe('#3557 trust-policy helpers', () => { + it('reads trust from the claude-flow block, falling back to top-level fields', () => { + expect(readDeclaredTrust({ 'claude-flow': { trustLevel: 'untrusted', permissions: ['shell:exec'] } })) + .toEqual({ trustLevel: 'untrusted', permissions: ['shell:exec'] }); + expect(readDeclaredTrust({ trustLevel: 'community', permissions: ['memory:read'] })) + .toEqual({ trustLevel: 'community', permissions: ['memory:read'] }); + expect(readDeclaredTrust({})).toEqual({ trustLevel: undefined, permissions: [] }); + }); + + it('a registry-vouched (official/verified) plugin is allowed without --trust', () => { + const d = evaluatePluginTrust( + { permissions: ['memory', 'hooks'] }, + { verify: true, trust: false, registryTrustLevel: 'official' }, + ); + expect(d.allowed).toBe(true); + }); + + it('only a well-formed sha256 digest is verifiable', () => { + expect(parseSha256Checksum(`sha256:${'a'.repeat(64)}`)).toBe('a'.repeat(64)); + expect(parseSha256Checksum('sha256:abc123neural')).toBeNull(); + expect(parseSha256Checksum(undefined)).toBeNull(); + }); +}); diff --git a/v3/@claude-flow/cli/src/commands/plugins.ts b/v3/@claude-flow/cli/src/commands/plugins.ts index 2003e97910..e989e46c07 100644 --- a/v3/@claude-flow/cli/src/commands/plugins.ts +++ b/v3/@claude-flow/cli/src/commands/plugins.ts @@ -20,6 +20,7 @@ import { type PluginType, } from '../plugins/store/index.js'; import { getPluginManager, type InstalledPlugin } from '../plugins/manager.js'; +import { DEFAULT_PLUGIN_PERMISSIONS } from '../plugins/trust-policy.js'; import { getBulkRatings } from '../services/registry-api.js'; // List subcommand - Now uses IPFS-based registry @@ -214,18 +215,30 @@ const installCommand: Command = { { name: 'version', short: 'v', type: 'string', description: 'Specific version to install' }, { name: 'global', short: 'g', type: 'boolean', description: 'Install globally' }, { name: 'dev', short: 'd', type: 'boolean', description: 'Install as dev dependency' }, - { name: 'verify', type: 'boolean', description: 'Verify checksum (default: true)', default: true }, + { + name: 'verify', + type: 'boolean', + description: + 'Verify before registering (default: true). Registry installs must match the registry sha256 checksum. ' + + 'Hooks and commands are withheld from a plugin that declares trustLevel "untrusted"/"unverified" or ' + + `permissions beyond the default set (${DEFAULT_PLUGIN_PERMISSIONS.join(', ')}) unless --trust is given. ` + + '--no-verify skips all of this.', + default: true, + }, + { name: 'trust', type: 'boolean', description: 'Register hooks and commands even if the plugin is untrusted or declares elevated permissions', default: false }, { name: 'registry', short: 'r', type: 'string', description: 'Registry to use' }, ], examples: [ { command: 'claude-flow plugins install -n community-analytics', description: 'Install plugin from IPFS' }, { command: 'claude-flow plugins install -n ./my-plugin --dev', description: 'Install local plugin' }, + { command: 'claude-flow plugins install -n ./my-plugin --trust', description: 'Install a local plugin that declares elevated permissions, registering its hooks' }, ], action: async (ctx: CommandContext): Promise => { const name = ctx.flags.name as string; const version = ctx.flags.version as string || 'latest'; const registryName = ctx.flags.registry as string; const verify = ctx.flags.verify !== false; + const trust = ctx.flags.trust === true; if (!name) { output.printError('Plugin name is required'); @@ -264,7 +277,7 @@ const installCommand: Command = { if (isLocalPath) { // Install from local path spinner.setText(`Installing from ${name}...`); - result = await manager.installFromLocal(name); + result = await manager.installFromLocal(name, { verify, trust }); } else { // First, try to find in registry for metadata spinner.setText(`Discovering ${name} in registry...`); @@ -281,7 +294,13 @@ const installCommand: Command = { // Install from npm (since IPFS is demo mode) spinner.setText(`Installing ${name} from npm...`); - result = await manager.installFromNpm(name, version !== 'latest' ? version : undefined); + result = await manager.installFromNpm(name, version !== 'latest' ? version : undefined, { + verify, + trust, + expectedChecksum: plugin?.checksum, + registryTrustLevel: plugin?.trustLevel, + registryPermissions: plugin?.permissions, + }); } if (!result.success) { @@ -294,23 +313,44 @@ const installCommand: Command = { output.writeln(); + if (result.decision?.verificationSkipped) { + output.printWarning('Verification skipped (--no-verify): hooks and commands were registered without a trust or checksum check.'); + } + for (const warning of result.warnings ?? []) { + output.printWarning(warning); + } + const boxContent = [ `Plugin: ${installed.name}`, `Version: ${installed.version}`, `Source: ${installed.source}`, `Path: ${installed.path || 'N/A'}`, ``, + `Trust: ${installed.trustLevel ?? 'not declared'}`, + `Permissions: ${installed.permissions?.join(', ') || 'none declared'}`, + `Verification: ${installed.verification ?? 'n/a'}`, + ``, `Hooks registered: ${installed.hooks?.length || 0}`, `Commands added: ${installed.commands?.length || 0}`, ]; - if (plugin) { - boxContent.push(`Trust: ${plugin.trustLevel}`); - boxContent.push(`Permissions: ${plugin.permissions.join(', ') || 'none'}`); - } - output.printBox(boxContent.join('\n'), 'Installation Complete'); + if (installed.withheld) { + output.writeln(); + output.printWarning( + `Withheld ${installed.withheld.hooks.length} hook(s) and ${installed.withheld.commands.length} command(s) ` + + `from ${installed.name} because it ${installed.withheld.reasons.join('; ')}.`, + ); + if (installed.withheld.hooks.length > 0) { + output.writeln(output.dim(` Hooks not registered: ${installed.withheld.hooks.join(', ')}`)); + } + if (installed.withheld.commands.length > 0) { + output.writeln(output.dim(` Commands not added: ${installed.withheld.commands.join(', ')}`)); + } + output.writeln(output.dim(` To register them, uninstall and reinstall with --trust.`)); + } + return { success: true, data: installed }; } catch (error) { spinner.fail('Installation failed'); diff --git a/v3/@claude-flow/cli/src/plugins/manager.ts b/v3/@claude-flow/cli/src/plugins/manager.ts index 562dd2b67f..4580a6994c 100644 --- a/v3/@claude-flow/cli/src/plugins/manager.ts +++ b/v3/@claude-flow/cli/src/plugins/manager.ts @@ -5,9 +5,17 @@ */ import * as fs from 'fs'; +import * as os from 'os'; import * as path from 'path'; import { execFile } from 'child_process'; import { promisify } from 'util'; +import { + evaluatePluginTrust, + parseSha256Checksum, + readDeclaredTrust, + sha256Hex, + type TrustDecision, +} from './trust-policy.js'; const execFileAsync = promisify(execFile); @@ -36,6 +44,37 @@ function validatePackageName(spec: string): void { } } +/** + * Apply the #3557 trust policy to a plugin's package.json: record its declared + * trust and permissions, and withhold hooks/commands the policy doesn't allow. + */ +function applyTrustPolicy( + pkg: Record, + opts: PluginInstallOptions, +): Pick & { decision: TrustDecision } { + const block = (pkg['claude-flow'] ?? {}) as { commands?: unknown; hooks?: unknown }; + const commands = Array.isArray(block.commands) ? (block.commands as string[]) : []; + const hooks = Array.isArray(block.hooks) ? (block.hooks as string[]) : []; + const declared = readDeclaredTrust(pkg); + const permissions = [...new Set([...(opts.registryPermissions ?? []), ...declared.permissions])]; + const trustLevel = opts.registryTrustLevel ?? declared.trustLevel; + const decision = evaluatePluginTrust( + { trustLevel: declared.trustLevel, permissions }, + { verify: opts.verify !== false, trust: opts.trust === true, registryTrustLevel: opts.registryTrustLevel }, + ); + if (decision.allowed) { + return { commands, hooks, trustLevel, permissions, decision }; + } + return { + commands: [], + hooks: [], + trustLevel, + permissions, + withheld: { hooks, commands, reasons: decision.reasons }, + decision, + }; +} + // ============================================================================ // Types // ============================================================================ @@ -50,6 +89,36 @@ export interface InstalledPlugin { commands?: string[]; hooks?: string[]; config?: Record; + /** Declared (or registry-assigned) trust level, recorded at install time. */ + trustLevel?: string; + /** Declared permissions, recorded at install time so they can be enforced. */ + permissions?: string[]; + /** How the install was verified. */ + verification?: 'checksum' | 'npm-integrity' | 'policy' | 'skipped'; + /** Hooks/commands the plugin declared but that were not registered, and why. */ + withheld?: { hooks: string[]; commands: string[]; reasons: string[] }; +} + +/** Options for {@link PluginManager.installFromLocal} / {@link PluginManager.installFromNpm}. */ +export interface PluginInstallOptions { + /** `--verify` (default true). */ + verify?: boolean; + /** `--trust` (default false). */ + trust?: boolean; + /** Registry checksum (`sha256:`) the downloaded tarball must match. */ + expectedChecksum?: string; + /** Trust level from the registry entry, when the plugin was found there. */ + registryTrustLevel?: string; + /** Permissions from the registry entry, merged with the package's own declaration. */ + registryPermissions?: string[]; +} + +export interface PluginInstallResult { + success: boolean; + error?: string; + plugin?: InstalledPlugin; + decision?: TrustDecision; + warnings?: string[]; } export interface InstalledPluginsManifest { @@ -148,13 +217,17 @@ export class PluginManager { */ async installFromNpm( packageName: string, - version?: string - ): Promise<{ success: boolean; error?: string; plugin?: InstalledPlugin }> { + version?: string, + opts: PluginInstallOptions = {}, + ): Promise { if (!this.manifest) { await this.initialize(); } const versionSpec = version ? `${packageName}@${version}` : packageName; + const verify = opts.verify !== false; + const warnings: string[] = []; + let tmpDir: string | undefined; try { // Check if already installed @@ -172,28 +245,54 @@ export class PluginManager { // Validate package name to prevent injection (S-3) validatePackageName(versionSpec); + // #3557: with --verify, a registry checksum must match the tarball we + // install. Pack first, hash that exact file, then install from it, so the + // bytes that were checked are the bytes that get installed. + let installTarget = versionSpec; + let verification: InstalledPlugin['verification'] = verify ? 'npm-integrity' : 'skipped'; + const expected = verify ? parseSha256Checksum(opts.expectedChecksum) : null; + if (expected) { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ruflo-plugin-verify-')); + const packed = await runNpm(['pack', versionSpec, '--pack-destination', tmpDir, '--json'], 120000); + const info = JSON.parse(packed.stdout) as Array<{ filename?: string }>; + const filename = info[0]?.filename; + if (!filename) throw new Error(`npm pack returned no tarball for ${versionSpec}`); + const tarball = path.join(tmpDir, path.basename(filename)); + const actual = sha256Hex(fs.readFileSync(tarball)); + if (actual !== expected) { + return { + success: false, + error: + `Checksum mismatch for ${versionSpec}: registry expects sha256:${expected}, ` + + `downloaded tarball is sha256:${actual}. Refusing to install (--verify).`, + }; + } + installTarget = tarball; + verification = 'checksum'; + } else if (verify && opts.expectedChecksum) { + warnings.push( + `Registry checksum "${opts.expectedChecksum}" is not a verifiable sha256 digest; ` + + `relying on npm's own registry integrity check.`, + ); + } + // Use npm to install (array form prevents shell injection) console.log(`[PluginManager] Installing ${versionSpec}...`); - await runNpm(['install', '--prefix', this.config.pluginsDir, versionSpec], 120000); + await runNpm(['install', '--prefix', this.config.pluginsDir, installTarget], 120000); // Get installed version const packageJsonPath = path.join(installDir, packageName, 'package.json'); let installedVersion = version || 'latest'; - let commands: string[] = []; - let hooks: string[] = []; + let pkg: Record = {}; if (fs.existsSync(packageJsonPath)) { - const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')); - installedVersion = pkg.version; - - // Check for claude-flow plugin metadata - if (pkg['claude-flow']) { - commands = pkg['claude-flow'].commands || []; - hooks = pkg['claude-flow'].hooks || []; - } + pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')); + installedVersion = String(pkg.version ?? installedVersion); } + const trusted = applyTrustPolicy(pkg, opts); + // Create plugin entry const plugin: InstalledPlugin = { name: packageName, @@ -202,8 +301,12 @@ export class PluginManager { enabled: true, source: 'npm', path: path.join(installDir, packageName), - commands, - hooks, + commands: trusted.commands, + hooks: trusted.hooks, + trustLevel: trusted.trustLevel, + permissions: trusted.permissions, + verification, + ...(trusted.withheld ? { withheld: trusted.withheld } : {}), }; // Save to manifest @@ -212,11 +315,13 @@ export class PluginManager { console.log(`[PluginManager] Installed ${packageName}@${installedVersion}`); - return { success: true, plugin }; + return { success: true, plugin, decision: trusted.decision, warnings }; } catch (error) { const errorMsg = error instanceof Error ? error.message : String(error); console.error(`[PluginManager] Failed to install ${packageName}:`, errorMsg); return { success: false, error: errorMsg }; + } finally { + if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true }); } } @@ -224,8 +329,9 @@ export class PluginManager { * Install a plugin from a local path */ async installFromLocal( - sourcePath: string - ): Promise<{ success: boolean; error?: string; plugin?: InstalledPlugin }> { + sourcePath: string, + opts: PluginInstallOptions = {}, + ): Promise { if (!this.manifest) { await this.initialize(); } @@ -254,6 +360,11 @@ export class PluginManager { }; } + // #3557: record declared trust/permissions; withhold hooks and commands + // the policy doesn't allow without --trust. A local path has no registry + // entry to vouch for it, so the plugin's own declaration decides. + const trusted = applyTrustPolicy(pkg, { verify: opts.verify, trust: opts.trust }); + // Create plugin entry (link to local path, don't copy) const plugin: InstalledPlugin = { name: packageName, @@ -262,8 +373,12 @@ export class PluginManager { enabled: true, source: 'local', path: absolutePath, - commands: pkg['claude-flow']?.commands || [], - hooks: pkg['claude-flow']?.hooks || [], + commands: trusted.commands, + hooks: trusted.hooks, + trustLevel: trusted.trustLevel, + permissions: trusted.permissions, + verification: opts.verify === false ? 'skipped' : 'policy', + ...(trusted.withheld ? { withheld: trusted.withheld } : {}), }; // Save to manifest @@ -272,7 +387,7 @@ export class PluginManager { console.log(`[PluginManager] Installed local plugin ${packageName}@${pkg.version}`); - return { success: true, plugin }; + return { success: true, plugin, decision: trusted.decision }; } catch (error) { const errorMsg = error instanceof Error ? error.message : String(error); console.error(`[PluginManager] Failed to install from local:`, errorMsg); diff --git a/v3/@claude-flow/cli/src/plugins/trust-policy.ts b/v3/@claude-flow/cli/src/plugins/trust-policy.ts new file mode 100644 index 0000000000..66b2c1110f --- /dev/null +++ b/v3/@claude-flow/cli/src/plugins/trust-policy.ts @@ -0,0 +1,109 @@ +/** + * Plugin install trust policy (#3557). + * + * `plugins install --verify` used to be parsed and never read, and a plugin's + * declared `trustLevel`/`permissions` were neither recorded nor enforced. + * These pure helpers decide what an install may register. + */ + +import { createHash } from 'crypto'; + +/** + * Permissions a plugin may declare and still have its hooks and commands + * registered without `--trust`. Anything else (filesystem, network, shell, + * secrets, config, privileged, …) needs an explicit `--trust`. + */ +export const DEFAULT_PLUGIN_PERMISSIONS: readonly string[] = Object.freeze(['memory:read']); + +/** Trust levels that are withheld unless the user passes `--trust`. */ +export const UNTRUSTED_TRUST_LEVELS: readonly string[] = Object.freeze(['untrusted', 'unverified']); + +/** Registry trust levels that the registry itself vouches for. */ +export const REGISTRY_VOUCHED_TRUST_LEVELS: readonly string[] = Object.freeze(['official', 'verified']); + +export interface DeclaredTrust { + trustLevel?: string; + permissions: string[]; +} + +export interface TrustDecision { + /** Hooks and commands may be registered. */ + allowed: boolean; + /** Verification was skipped with `--no-verify`. */ + verificationSkipped: boolean; + /** Why registration was withheld (empty when allowed). */ + reasons: string[]; + /** Declared permissions outside {@link DEFAULT_PLUGIN_PERMISSIONS}. */ + excessPermissions: string[]; +} + +export interface TrustOptions { + /** `--verify` (default true). */ + verify: boolean; + /** `--trust` (default false). */ + trust: boolean; + /** Trust level from a registry entry, when the plugin was found there. */ + registryTrustLevel?: string; +} + +function asStringList(value: unknown): string[] { + if (!Array.isArray(value)) return []; + return value.filter((v): v is string => typeof v === 'string' && v.trim() !== '').map((v) => v.trim()); +} + +/** + * Read the trust declaration from a plugin's package.json. The `claude-flow` + * block wins; top-level fields are accepted as a fallback. + */ +export function readDeclaredTrust(pkg: Record): DeclaredTrust { + const block = (pkg['claude-flow'] && typeof pkg['claude-flow'] === 'object' + ? pkg['claude-flow'] + : {}) as Record; + const trustLevel = typeof block.trustLevel === 'string' + ? block.trustLevel + : typeof pkg.trustLevel === 'string' ? pkg.trustLevel : undefined; + const permissions = asStringList(block.permissions).length > 0 + ? asStringList(block.permissions) + : asStringList(pkg.permissions); + return { trustLevel, permissions }; +} + +/** Decide whether an install may register the plugin's hooks and commands. */ +export function evaluatePluginTrust(declared: DeclaredTrust, opts: TrustOptions): TrustDecision { + const excessPermissions = declared.permissions.filter((p) => !DEFAULT_PLUGIN_PERMISSIONS.includes(p)); + + if (!opts.verify) { + return { allowed: true, verificationSkipped: true, reasons: [], excessPermissions }; + } + + const reasons: string[] = []; + const registryVouched = opts.registryTrustLevel !== undefined + && REGISTRY_VOUCHED_TRUST_LEVELS.includes(opts.registryTrustLevel); + + if (!registryVouched) { + if (declared.trustLevel && UNTRUSTED_TRUST_LEVELS.includes(declared.trustLevel)) { + reasons.push(`declares trustLevel "${declared.trustLevel}"`); + } + if (excessPermissions.length > 0) { + reasons.push( + `declares permissions beyond the default set (${DEFAULT_PLUGIN_PERMISSIONS.join(', ')}): ${excessPermissions.join(', ')}`, + ); + } + } + + if (reasons.length > 0 && !opts.trust) { + return { allowed: false, verificationSkipped: false, reasons, excessPermissions }; + } + return { allowed: true, verificationSkipped: false, reasons: [], excessPermissions }; +} + +/** A registry checksum we can actually verify: `sha256:` + 64 hex chars. */ +export function parseSha256Checksum(checksum: unknown): string | null { + if (typeof checksum !== 'string') return null; + const m = /^sha256:([0-9a-f]{64})$/i.exec(checksum.trim()); + return m ? m[1].toLowerCase() : null; +} + +export function sha256Hex(data: Buffer): string { + return createHash('sha256').update(data).digest('hex'); +}