π 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(plugins): fail closed when the plugin registry is not verified
Dragan Spiridonovc4c66b2c7b11
diff --git a/v3/@claude-flow/cli/__tests__/plugins-registry-trust-fail-closed.test.ts b/v3/@claude-flow/cli/__tests__/plugins-registry-trust-fail-closed.test.tsnew file mode 100644index 0000000000..6c6d2382de--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/plugins-registry-trust-fail-closed.test.ts@@ -0,0 +1,255 @@+/**+ * Plugin registry trust fails closed (ADR-145).+ *+ * The signed registry is what vouches for a plugin: its trustLevel 'official'/'verified' lets an+ * install run npm lifecycle scripts and skip the permission gate. So:+ * - an unverified registry (unsigned, bad signature, placeholder pinned key, verification off)+ * and the built-in fallback list carry no registry trust;+ * - a placeholder (all-zero) pinned key is never used to verify β it accepts a forged signature;+ * - CLAUDE_FLOW_STRICT_PLUGINS=true turns the fallback into an error and makes `plugins install`+ * refuse without --allow-unverified;+ * - `plugins install` never passes an unverified entry's trust, permissions or checksum on.+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const ipfs = vi.hoisted(() => ({ registry: null as Record<string, unknown> | null }));++vi.mock('../src/transfer/ipfs/client.js', async (importOriginal) => {+ const real = await importOriginal<typeof import('../src/transfer/ipfs/client.js')>();+ return {+ ...real,+ resolveIPNS: vi.fn(async () => null),+ fetchFromIPFS: vi.fn(async () => ipfs.registry),+ };+});++const manager = vi.hoisted(() => ({+ installFromNpm: vi.fn(),+}));++vi.mock('../src/plugins/manager.js', () => ({+ getPluginManager: () => ({+ initialize: async () => {},+ getPlugin: async () => undefined,+ installFromNpm: manager.installFromNpm,+ getPluginsDir: () => '/tmp/plugins',+ }),+}));++import { PluginDiscoveryService } from '../src/plugins/store/discovery.js';+import { verifyEd25519Signature } from '../src/transfer/ipfs/client.js';+import { isPlaceholderSigningKey, isStrictPluginMode } from '../src/plugins/trust-policy.js';+import { pluginsCommand } from '../src/commands/plugins.js';+import type { CommandContext } from '../src/types.js';+import anchorsFile from '../src/plugins/trust/trust-anchors.json';++const ZERO_KEY = '0'.repeat(64);+// R = identity point, S = 0: verifies against any small-order key for every message (ZIP-215).+const FORGED_SIG = '01' + '0'.repeat(126);++function entry(name: string, trustLevel = 'official') {+ return {+ id: name,+ name,+ displayName: name,+ version: '1.0.0',+ trustLevel,+ verified: true,+ checksum: 'sha256:' + 'a'.repeat(64),+ permissions: ['shell:exec'],+ hooks: [],+ commands: [],+ };+}++function registryWith(plugins: ReturnType<typeof entry>[], extra: Record<string, unknown> = {}) {+ return {+ version: '1.0.1',+ type: 'plugins',+ plugins,+ totalPlugins: plugins.length,+ featured: [],+ official: plugins.map((p) => p.id),+ ...extra,+ };+}++function serviceFor(publicKey: string, overrides: Record<string, unknown> = {}) {+ return new PluginDiscoveryService({+ requireVerification: true,+ defaultRegistry: 'test',+ registries: [+ { name: 'test', description: 't', ipnsName: 'QmTestRegistry', gateway: 'https://example.invalid', publicKey, trusted: true, official: true },+ ],+ ...overrides,+ } as never);+}++async function signRegistry(registry: Record<string, unknown>) {+ const ed = await import('@noble/ed25519');+ const priv = ed.utils.randomPrivateKey();+ const pub = Buffer.from(await ed.getPublicKeyAsync(priv)).toString('hex');+ const sig = await ed.signAsync(new TextEncoder().encode(JSON.stringify(registry)), priv);+ return { pub, signed: { ...registry, registrySignature: Buffer.from(sig).toString('hex') } };+}++beforeEach(() => {+ vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('offline'); }));+ vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ vi.spyOn(console, 'error').mockImplementation(() => {});+ delete process.env.CLAUDE_FLOW_STRICT_PLUGINS;+ ipfs.registry = null;+ manager.installFromNpm.mockReset();+});++afterEach(() => {+ delete process.env.CLAUDE_FLOW_STRICT_PLUGINS;+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe('placeholder signing keys', () => {+ it('the shipped trust anchor is a placeholder', () => {+ expect(anchorsFile.anchors.length).toBeGreaterThan(0);+ for (const a of anchorsFile.anchors) expect(isPlaceholderSigningKey(a.publicKey)).toBe(true);+ });++ it('rejects missing, malformed and all-zero keys; accepts a real-looking key', () => {+ expect(isPlaceholderSigningKey(undefined)).toBe(true);+ expect(isPlaceholderSigningKey('')).toBe(true);+ expect(isPlaceholderSigningKey('ed25519:abc')).toBe(true);+ expect(isPlaceholderSigningKey(`ed25519:${ZERO_KEY}`)).toBe(true);+ expect(isPlaceholderSigningKey(`ed25519:${'ab'.repeat(32)}`)).toBe(false);+ });++ it('the all-zero key really does accept a forged signature (why it must never be verified against)', async () => {+ expect(await verifyEd25519Signature('any message at all', FORGED_SIG, ZERO_KEY)).toBe(true);+ });++ it('a placeholder pinned key leaves the registry unverified even with a "valid" forged signature', async () => {+ ipfs.registry = registryWith([entry('@claude-flow/evil')], { registrySignature: FORGED_SIG });+ const result = await serviceFor(`ed25519:${ZERO_KEY}`).discoverRegistry();++ expect(result.verified).toBe(false);+ expect(result.unverifiedReason).toMatch(/placeholder/);+ expect(result.registry!.plugins.find((p) => p.name === '@claude-flow/evil')).toBeUndefined();+ expect(result.registry!.plugins.every((p) => p.trustLevel === 'unverified' && !p.verified)).toBe(true);+ });+});++describe('discovery: an unverified registry confers no trust', () => {+ it('an unsigned registry falls back to the built-in list, labelled demo and unverified, with trust stripped', async () => {+ ipfs.registry = registryWith([entry('@claude-flow/a')]);+ const svc = serviceFor(`ed25519:${'ab'.repeat(32)}`);++ const first = await svc.discoverRegistry();+ expect(first.success).toBe(true);+ expect(first.demo).toBe(true);+ expect(first.verified).toBe(false);+ expect(first.unverifiedReason).toMatch(/unsigned/);+ expect(first.registry!.plugins.length).toBeGreaterThan(0);+ expect(first.registry!.plugins.every((p) => p.trustLevel === 'unverified' && !p.verified)).toBe(true);++ const second = await svc.discoverRegistry();+ expect(second.fromCache).toBe(true);+ expect(second.verified).toBe(false);+ expect(second.registry!.plugins.every((p) => p.trustLevel === 'unverified')).toBe(true);+ });++ it('a signature that does not verify is not silently treated as the registry', async () => {+ const { signed } = await signRegistry(registryWith([entry('@claude-flow/a')]));+ ipfs.registry = signed;+ // Pinned key differs from the signer.+ const result = await serviceFor(`ed25519:${'ab'.repeat(32)}`).discoverRegistry();+ expect(result.verified).toBe(false);+ expect(result.demo).toBe(true);+ expect(result.unverifiedReason).toMatch(/does not verify/);+ });++ it('with verification disabled the fetched registry is used but every entry is unverified', async () => {+ ipfs.registry = registryWith([entry('@claude-flow/a')]);+ const result = await serviceFor(`ed25519:${'ab'.repeat(32)}`, { requireVerification: false }).discoverRegistry();+ expect(result.success).toBe(true);+ expect(result.demo).toBeUndefined();+ expect(result.verified).toBe(false);+ expect(result.registry!.plugins).toEqual([expect.objectContaining({ name: '@claude-flow/a', trustLevel: 'unverified', verified: false })]);+ });++ it('a correctly signed registry is verified and keeps its trust levels', async () => {+ const { pub, signed } = await signRegistry(registryWith([entry('@claude-flow/a')]));+ ipfs.registry = signed;+ const result = await serviceFor(`ed25519:${pub}`).discoverRegistry();+ expect(result.verified).toBe(true);+ expect(result.demo).toBeUndefined();+ expect(result.unverifiedReason).toBeUndefined();+ expect(result.registry!.plugins[0].trustLevel).toBe('official');+ });++ it('CLAUDE_FLOW_STRICT_PLUGINS=true: no fallback, discovery fails with the reason', async () => {+ process.env.CLAUDE_FLOW_STRICT_PLUGINS = 'true';+ expect(isStrictPluginMode()).toBe(true);+ ipfs.registry = registryWith([entry('@claude-flow/a')]);+ const result = await serviceFor(`ed25519:${'ab'.repeat(32)}`).discoverRegistry();+ expect(result.success).toBe(false);+ expect(result.registry).toBeUndefined();+ expect(result.verified).toBe(false);+ expect(result.error).toMatch(/unsigned.*CLAUDE_FLOW_STRICT_PLUGINS=true/);+ });+});++describe('plugins install: unverified registry entries get no registry trust', () => {+ const install = pluginsCommand.subcommands!.find((c) => c.name === 'install')!;+ const ctxFor = (flags: Record<string, unknown>) =>+ ({ args: [], flags: { _: [], ...flags }, cwd: process.cwd(), interactive: false }) as unknown as CommandContext;+ const installed = { success: true, plugin: { name: '@claude-flow/neural', version: '3.0.0', source: 'npm' }, warnings: [] };++ // The real default registry is unsigned today, as the live CID is; serve it unsigned.+ beforeEach(() => {+ ipfs.registry = registryWith([entry('@claude-flow/neural')]);+ manager.installFromNpm.mockResolvedValue(installed);+ });++ it('default mode: a built-in-list entry installs without its "official" trust, permissions or checksum', async () => {+ const res = await install.action!(ctxFor({ name: '@claude-flow/neural' }));+ expect(res.success).toBe(true);+ expect(manager.installFromNpm).toHaveBeenCalledTimes(1);+ const opts = manager.installFromNpm.mock.calls[0][2];+ expect(opts).toEqual({ verify: true, trust: false });+ });++ it('strict mode: refuses without --allow-unverified and installs nothing', async () => {+ process.env.CLAUDE_FLOW_STRICT_PLUGINS = 'true';+ const res = await install.action!(ctxFor({ name: '@claude-flow/neural' }));+ expect(res.success).toBe(false);+ expect(manager.installFromNpm).not.toHaveBeenCalled();+ });++ it('strict mode + --allow-unverified: installs, still without registry trust', async () => {+ process.env.CLAUDE_FLOW_STRICT_PLUGINS = 'true';+ const res = await install.action!(ctxFor({ name: '@claude-flow/neural', allowUnverified: true }));+ expect(res.success).toBe(true);+ expect(manager.installFromNpm.mock.calls[0][2]).toEqual({ verify: true, trust: false });+ });++ it('a verified registry entry still passes its trust, permissions and checksum on', async () => {+ const { pub, signed } = await signRegistry(registryWith([entry('@claude-flow/neural')]));+ ipfs.registry = signed;+ const { DEFAULT_PLUGIN_STORE_CONFIG } = await import('../src/plugins/store/discovery.js');+ const original = DEFAULT_PLUGIN_STORE_CONFIG.registries.map((r) => r.publicKey);+ DEFAULT_PLUGIN_STORE_CONFIG.registries.forEach((r) => { r.publicKey = `ed25519:${pub}`; });+ try {+ const res = await install.action!(ctxFor({ name: '@claude-flow/neural' }));+ expect(res.success).toBe(true);+ expect(manager.installFromNpm.mock.calls[0][2]).toEqual({+ verify: true,+ trust: false,+ expectedChecksum: 'sha256:' + 'a'.repeat(64),+ registryTrustLevel: 'official',+ registryPermissions: ['shell:exec'],+ });+ } finally {+ DEFAULT_PLUGIN_STORE_CONFIG.registries.forEach((r, i) => { r.publicKey = original[i]; });+ }+ });+});diff --git a/v3/@claude-flow/cli/src/commands/plugins.ts b/v3/@claude-flow/cli/src/commands/plugins.tsindex 60b6238edc..f7d94a7b58 100644--- a/v3/@claude-flow/cli/src/commands/plugins.ts+++ b/v3/@claude-flow/cli/src/commands/plugins.ts@@ -20,7 +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 { DEFAULT_PLUGIN_PERMISSIONS, isStrictPluginMode } from '../plugins/trust-policy.js';import { getBulkRatings } from '../services/registry-api.js';// List subcommand - Now uses IPFS-based registry@@ -117,6 +117,10 @@ const listCommand: Command = {`(${result.registry.totalPlugins} plugins)`,),);+ } else if (result.verified !== true) {+ spinner.stop(+ output.warning(`Registry discovered but not verified: ${result.registry.totalPlugins} plugins available`),+ );} else {spinner.succeed(`Registry discovered: ${result.registry.totalPlugins} plugins available`);}@@ -207,11 +211,19 @@ const listCommand: Command = {if (result.demo) {output.writeln(output.warning(- 'Not from the signed registry: download counts, ratings and trust labels are the ' ++ 'Not from the signed registry: download counts and ratings are the ' +"CLI's built-in defaults, not verified registry data.",),);}+ if (result.verified !== true) {+ output.writeln(+ output.warning(+ `Registry not verified (${result.unverifiedReason ?? 'unknown reason'}): every entry is ` ++ 'shown as Unverified and installs get no registry trust.',+ ),+ );+ }if (result.cid) {output.writeln(output.dim(`Registry CID: ${result.cid.slice(0, 30)}...`));}@@ -245,6 +257,14 @@ const installCommand: Command = {default: true,},{ name: 'trust', type: 'boolean', description: 'Register hooks and commands even if the plugin is untrusted or declares elevated permissions', default: false },+ {+ name: 'allow-unverified',+ type: 'boolean',+ description:+ 'With CLAUDE_FLOW_STRICT_PLUGINS=true, install from npm even though the plugin registry is not verified. ' ++ 'The plugin still gets no registry trust.',+ default: false,+ },{ name: 'registry', short: 'r', type: 'string', description: 'Registry to use' },],examples: [@@ -258,6 +278,7 @@ const installCommand: Command = {const registryName = ctx.flags.registry as string;const verify = ctx.flags.verify !== false;const trust = ctx.flags.trust === true;+ const allowUnverified = ctx.flags.allowUnverified === true || ctx.flags['allow-unverified'] === true;if (!name) {output.printError('Plugin name is required');@@ -292,6 +313,7 @@ const installCommand: Command = {let result;let plugin: PluginEntry | undefined;+ const registryWarnings: string[] = [];if (isLocalPath) {// Install from local path@@ -307,18 +329,43 @@ const installCommand: Command = {plugin = registryResult.registry.plugins.find(p => p.name === name || p.id === name);}+ // Only a verified registry may vouch for a plugin (trust level, permissions, checksum).+ // An unverified or built-in list is just a claim, so its entries install like any npm+ // package: no install scripts and no permission vouching without --trust.+ const registryVerified = registryResult.success && registryResult.verified === true;+ if (!registryVerified) {+ const reason = registryResult.unverifiedReason ?? registryResult.error ?? 'registry not verified';+ if (isStrictPluginMode() && !allowUnverified) {+ spinner.fail(`Refusing to install ${name}: plugin registry is not verified (${reason})`);+ output.writeln();+ output.writeln(output.dim(+ 'CLAUDE_FLOW_STRICT_PLUGINS=true requires a verified registry. Pass --allow-unverified to install it ' ++ 'from npm anyway, without registry trust.',+ ));+ return { success: false, exitCode: 1 };+ }+ if (plugin) {+ registryWarnings.push(+ `${name} is listed only in an unverified registry (${reason}); it was installed without registry trust.`,+ );+ }+ }+if (plugin) {spinner.setText(`Found ${plugin.displayName} v${plugin.version}`);}- // Install from npm (since IPFS is demo mode)spinner.setText(`Installing ${name} from npm...`);result = await manager.installFromNpm(name, version !== 'latest' ? version : undefined, {verify,trust,- expectedChecksum: plugin?.checksum,- registryTrustLevel: plugin?.trustLevel,- registryPermissions: plugin?.permissions,+ ...(registryVerified && plugin+ ? {+ expectedChecksum: plugin.checksum,+ registryTrustLevel: plugin.trustLevel,+ registryPermissions: plugin.permissions,+ }+ : {}),});}@@ -335,7 +382,7 @@ const installCommand: Command = {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 ?? []) {+ for (const warning of [...registryWarnings, ...(result.warnings ?? [])]) {output.printWarning(warning);}@@ -535,6 +582,7 @@ const infoCommand: Command = {if (!result.success || !result.registry) {spinner.fail('Failed to discover registry');+ if (result.error) output.printError(result.error);return { success: false, exitCode: 1 };}@@ -571,6 +619,7 @@ const infoCommand: Command = {{ field: 'Author', value: plugin.author.displayName || plugin.author.id },{ field: 'Trust Level', value: plugin.trustLevel },{ field: 'Verified', value: plugin.verified ? 'β Yes' : 'β No' },+ { field: 'Registry', value: result.verified === true ? 'verified' : `unverified (${result.unverifiedReason ?? 'unknown reason'})` },],});@@ -861,6 +910,7 @@ const searchCommand: Command = {if (!result.success || !result.registry) {spinner.fail('Failed to discover registry');+ if (result.error) output.printError(result.error);return { success: false, exitCode: 1 };}diff --git a/v3/@claude-flow/cli/src/plugins/store/discovery.ts b/v3/@claude-flow/cli/src/plugins/store/discovery.tsindex b0a8c8a122..b270172d92 100644--- a/v3/@claude-flow/cli/src/plugins/store/discovery.ts+++ b/v3/@claude-flow/cli/src/plugins/store/discovery.ts@@ -14,6 +14,7 @@ import type {PluginEntry,} from './types.js';import { resolveIPNS, fetchFromIPFS, verifyEd25519Signature } from '../../transfer/ipfs/client.js';+import { isPlaceholderSigningKey, isStrictPluginMode } from '../trust-policy.js';/*** Fetch real npm download stats for a package@@ -118,6 +119,25 @@ export interface PluginDiscoveryResult {* is NOT the verified registry, and callers must say so rather than report a discovery.*/demo?: boolean;+ /**+ * True only when the registry's signature verified against the pinned key. Entries of an+ * unverified registry carry no registry trust: their trustLevel is reported as+ * 'unverified', so nothing downstream can treat them as registry-vouched.+ */+ verified?: boolean;+ /** Why the registry is not verified (set whenever `verified` is not true). */+ unverifiedReason?: string;+}++/**+ * Strip registry-asserted trust from a registry that was not verified. Its trust labels are+ * just claims made by whoever served (or hardcoded) the list.+ */+function withoutRegistryTrust(registry: PluginRegistry): PluginRegistry {+ return {+ ...registry,+ plugins: registry.plugins.map((p) => ({ ...p, trustLevel: 'unverified' as const, verified: false })),+ };}/**@@ -125,12 +145,26 @@ export interface PluginDiscoveryResult {*/export class PluginDiscoveryService {private config: PluginStoreConfig;- private cache: Map<string, { registry: PluginRegistry; timestamp: number; demo?: boolean }> = new Map();+ private cache: Map<string, {+ registry: PluginRegistry;+ timestamp: number;+ demo?: boolean;+ verified?: boolean;+ unverifiedReason?: string;+ }> = new Map();constructor(config: Partial<PluginStoreConfig> = {}) {this.config = { ...DEFAULT_PLUGIN_STORE_CONFIG, ...config };}+ /**+ * Whether an unverified registry may be replaced by the built-in list. Off under+ * `CLAUDE_FLOW_STRICT_PLUGINS=true` (ADR-145) unless the config says otherwise.+ */+ private allowsUnverifiedFallback(): boolean {+ return this.config.allowUnverifiedFallback ?? !isStrictPluginMode();+ }+/*** Discover plugin registry via IPNS*/@@ -153,11 +187,13 @@ export class PluginDiscoveryService {console.log(`[PluginDiscovery] Cache hit for ${registry.name}`);return {success: true,- registry: cached.registry,+ registry: cached.verified ? cached.registry : withoutRegistryTrust(cached.registry),fromCache: true,// A cached fallback is still the fallback: never relabel it as the real registry.source: cached.demo ? `${registry.name} (demo)` : registry.name,...(cached.demo ? { demo: true } : {}),+ verified: cached.verified === true,+ ...(cached.verified ? {} : { unverifiedReason: cached.unverifiedReason ?? 'registry not verified' }),};}@@ -174,8 +210,7 @@ export class PluginDiscoveryService {// Resolve IPNS to get current CIDcid = await resolveIPNS(registry.ipnsName, registry.gateway);if (!cid) {- // Fallback to demo registry- return this.createDemoRegistryAsync(registry);+ return this.fallbackToBuiltIn(registry, `could not resolve IPNS name ${registry.ipnsName}`);}console.log(`[PluginDiscovery] Resolved IPNS to CID: ${cid}`);}@@ -183,7 +218,7 @@ export class PluginDiscoveryService {// Fetch registry from IPFSconst registryData = await fetchFromIPFS<PluginRegistry>(cid, registry.gateway);if (!registryData) {- return this.createDemoRegistryAsync(registry);+ return this.fallbackToBuiltIn(registry, `could not fetch registry CID ${cid}`);}// Verify registry signature when required.@@ -192,20 +227,35 @@ export class PluginDiscoveryService {// on-path attacker) swap in attacker-mapped plugin entries that the// installer would then load unsandboxed.if (this.config.requireVerification) {- const verified = await this.verifyRegistrySignature(registryData, registry.publicKey);- if (!verified) {- console.warn(- `[PluginDiscovery] Registry signature verification failed for ` +- `${registry.name} (CID ${cid}); falling back to demo registry.`,- );- return this.createDemoRegistryAsync(registry);+ const failure = await this.registrySignatureFailure(registryData, registry.publicKey);+ if (failure) {+ return this.fallbackToBuiltIn(registry, `${failure}, CID ${cid}`);}+ } else {+ // Verification disabled by config: usable, but it vouches for nothing.+ const unverifiedReason = 'signature verification disabled (requireVerification: false)';+ this.cache.set(registry.ipnsName, {+ registry: registryData,+ timestamp: Date.now(),+ verified: false,+ unverifiedReason,+ });+ return {+ success: true,+ registry: withoutRegistryTrust(registryData),+ cid,+ source: registry.name,+ fromCache: false,+ verified: false,+ unverifiedReason,+ };}// Cache the resultthis.cache.set(registry.ipnsName, {registry: registryData,timestamp: Date.now(),+ verified: true,});return {@@ -214,12 +264,49 @@ export class PluginDiscoveryService {cid,source: registry.name,fromCache: false,+ verified: true,};} catch (error) {console.error(`[PluginDiscovery] Failed to discover registry:`, error);- // Return demo registry on error- return this.createDemoRegistryAsync(registry);+ return this.fallbackToBuiltIn(registry, `discovery error: ${error instanceof Error ? error.message : String(error)}`);+ }+ }++ /**+ * The signed registry is unavailable or unverified. Outside strict mode, use the built-in+ * list, labelled as such and stripped of registry trust; in strict mode, fail.+ */+ private async fallbackToBuiltIn(+ registry: KnownPluginRegistry,+ reason: string,+ ): Promise<PluginDiscoveryResult> {+ if (!this.allowsUnverifiedFallback()) {+ return {+ success: false,+ verified: false,+ unverifiedReason: reason,+ error:+ `Plugin registry ${registry.name} is not verified (${reason}). ` ++ 'Not falling back to the built-in plugin list because CLAUDE_FLOW_STRICT_PLUGINS=true.',+ };}++ console.warn(+ `[PluginDiscovery] Registry ${registry.name} is not verified (${reason}); ` ++ 'using the built-in plugin list, which is unverified and confers no registry trust.',+ );+ const result = await this.createDemoRegistryAsync(registry);+ const cached = this.cache.get(registry.ipnsName);+ if (cached) {+ cached.verified = false;+ cached.unverifiedReason = reason;+ }+ return {+ ...result,+ ...(result.registry ? { registry: withoutRegistryTrust(result.registry) } : {}),+ verified: false,+ unverifiedReason: reason,+ };}/**@@ -1158,7 +1245,7 @@ export class PluginDiscoveryService {}/**- * Verify registry Ed25519 signature.+ * Verify the registry Ed25519 signature; returns why it failed, or null when it verified.** Mirrors the signing scheme in scripts/publish-registry.ts: the signer* removes registrySignature + registryPublicKey from the registry object@@ -1168,12 +1255,17 @@ export class PluginDiscoveryService {* whoever served the registry and can be swapped by a compromised* gateway / on-path attacker.*/- private async verifyRegistrySignature(+ private async registrySignatureFailure(registry: PluginRegistry,expectedPublicKey: string,- ): Promise<boolean> {- if (!registry.registrySignature || !expectedPublicKey) {- return false;+ ): Promise<string | null> {+ // A placeholder pin (e.g. the all-zero key) can't vouch for anything, and the all-zero+ // key accepts a forged signature under ZIP-215 verification. Never verify against it.+ if (isPlaceholderSigningKey(expectedPublicKey)) {+ return 'pinned registry signing key is missing or a placeholder';+ }+ if (!registry.registrySignature) {+ return 'registry is unsigned';}// Object spread preserves insertion order; delete drops a key without// re-ordering the rest, matching the signer's view of the registry.@@ -1181,11 +1273,12 @@ export class PluginDiscoveryService {delete registryToVerify.registrySignature;delete registryToVerify.registryPublicKey;const message = JSON.stringify(registryToVerify);- return verifyEd25519Signature(+ const ok = await verifyEd25519Signature(message,registry.registrySignature,expectedPublicKey,);+ return ok ? null : 'registry signature does not verify against the pinned key';}/**diff --git a/v3/@claude-flow/cli/src/plugins/store/types.ts b/v3/@claude-flow/cli/src/plugins/store/types.tsindex 22ad7cf1ed..4facb91f3a 100644--- a/v3/@claude-flow/cli/src/plugins/store/types.ts+++ b/v3/@claude-flow/cli/src/plugins/store/types.ts@@ -319,6 +319,11 @@ export interface PluginStoreConfig {// SecurityrequireVerification: boolean;+ /**+ * Fall back to the built-in (unverified) plugin list when the signed registry can't be+ * verified. Defaults to true, or false under `CLAUDE_FLOW_STRICT_PLUGINS=true`.+ */+ allowUnverifiedFallback?: boolean;requireSecurityAudit: boolean;minTrustLevel: TrustLevel;trustedAuthors: string[];diff --git a/v3/@claude-flow/cli/src/plugins/trust-policy.ts b/v3/@claude-flow/cli/src/plugins/trust-policy.tsindex dbbc382c14..be69f3c20f 100644--- a/v3/@claude-flow/cli/src/plugins/trust-policy.ts+++ b/v3/@claude-flow/cli/src/plugins/trust-policy.ts@@ -119,3 +119,25 @@ export function parseSha256Checksum(checksum: unknown): string | null {export function sha256Hex(data: Buffer): string {return createHash('sha256').update(data).digest('hex');}++/**+ * Whether `CLAUDE_FLOW_STRICT_PLUGINS=true` (ADR-145): an unverified plugin+ * registry is then an error, not a warning.+ */+export function isStrictPluginMode(env: NodeJS.ProcessEnv = process.env): boolean {+ return (env.CLAUDE_FLOW_STRICT_PLUGINS ?? '').trim().toLowerCase() === 'true';+}++/**+ * A signing key that cannot vouch for anything: missing, not 32 bytes of hex,+ * or all zeros (the placeholder in `trust/trust-anchors.json`). The all-zero+ * key is also a small-order Ed25519 point, for which a fixed forged signature+ * verifies against every message under ZIP-215 rules, so it must never be+ * handed to a verifier.+ */+export function isPlaceholderSigningKey(key: unknown): boolean {+ if (typeof key !== 'string') return true;+ const hex = key.trim().replace(/^ed25519:/i, '');+ if (!/^[0-9a-f]{64}$/i.test(hex)) return true;+ return /^0+$/.test(hex);+}diff --git a/v3/@claude-flow/security/__tests__/plugin-integrity-verifier.test.ts b/v3/@claude-flow/security/__tests__/plugin-integrity-verifier.test.tsindex f2c28b29ef..a2c9602f53 100644--- a/v3/@claude-flow/security/__tests__/plugin-integrity-verifier.test.ts+++ b/v3/@claude-flow/security/__tests__/plugin-integrity-verifier.test.ts@@ -10,15 +10,20 @@* - verify reports `unknown-signer` when the key isn't in trust anchors* - verify reports `pass` on a valid round-trip sign β verify* - verify reports `signature-invalid` on a flipped signature byte+ * - the shipped placeholder (all-zero) anchor never vouches, and small-order+ * keys are rejected even when anchored (a forged R=identity, S=0 signature+ * verifies against them for every message under ZIP-215)*/import { describe, it, expect, beforeAll } from 'vitest';import { createHash } from 'node:crypto';+import { readFileSync } from 'node:fs';import {PluginIntegrityVerifier,canonicalize,hashManifest,findAnchor,+ isPlaceholderKey,type PluginManifest,type SignedPluginManifest,type TrustAnchor,@@ -197,3 +202,46 @@ describe('PluginIntegrityVerifier.verify', () => {expect(r.status).toBe('signature-invalid');});});++// βββ placeholder / small-order keys ββββββββββββββββββββββββββββββββββββ++describe('placeholder and small-order signing keys', () => {+ const ZERO_KEY = '0'.repeat(64);+ // y = -1: the order-2 point (0, -1).+ const ORDER_TWO_KEY = 'ec' + 'ff'.repeat(30) + '7f';+ // R = identity, S = 0.+ const FORGED_SIG = '01' + '0'.repeat(126);++ function forged(publicKey: string): SignedPluginManifest {+ const manifest = { id: '@claude-flow/evil', version: '6.6.6' };+ return { manifest, manifestHash: hashManifest(manifest), signature: FORGED_SIG, publicKey };+ }++ it('isPlaceholderKey flags empty and all-zero keys only', () => {+ expect(isPlaceholderKey('')).toBe(true);+ expect(isPlaceholderKey(ZERO_KEY)).toBe(true);+ expect(isPlaceholderKey(ORDER_TWO_KEY)).toBe(false);+ });++ it('the shipped trust-anchors.json placeholder never vouches for a forged manifest', async () => {+ const shipped = JSON.parse(+ readFileSync(new URL('../../cli/src/plugins/trust/trust-anchors.json', import.meta.url), 'utf-8'),+ ) as TrustAnchors;+ expect(shipped.anchors.some((a) => a.publicKey === ZERO_KEY)).toBe(true);+ expect(findAnchor(shipped.anchors, '@claude-flow/evil', ZERO_KEY, Date.now())).toBeNull();++ const r = await new PluginIntegrityVerifier({ trustAnchors: shipped }).verify(forged(ZERO_KEY));+ expect(r.status).not.toBe('pass');+ expect(r.status).toBe('unknown-signer');+ });++ it('rejects a forged signature even when a small-order key is anchored', async () => {+ if (!ed) { console.warn('@noble/ed25519 unavailable β skipping'); return; }+ // Sanity: noble's default (ZIP-215) verify accepts the forgery against this key.+ const m = forged(ORDER_TWO_KEY);+ expect(await ed.verifyAsync(hexBytes(FORGED_SIG), hexBytes(m.manifestHash), hexBytes(ORDER_TWO_KEY))).toBe(true);++ const r = await new PluginIntegrityVerifier({ trustAnchors: anchorsFor(ORDER_TWO_KEY) }).verify(m);+ expect(r.status).toBe('signature-invalid');+ });+});diff --git a/v3/@claude-flow/security/src/index.ts b/v3/@claude-flow/security/src/index.tsindex 8ef2d2d3b8..15e2fbf33e 100644--- a/v3/@claude-flow/security/src/index.ts+++ b/v3/@claude-flow/security/src/index.ts@@ -193,6 +193,7 @@ export {hashManifest,fingerprint,findAnchor,+ isPlaceholderKey,type PluginManifest,type SignedPluginManifest,type TrustAnchor,diff --git a/v3/@claude-flow/security/src/plugins/integrity-verifier.ts b/v3/@claude-flow/security/src/plugins/integrity-verifier.tsindex 850bf3d9db..e1cda4aad3 100644--- a/v3/@claude-flow/security/src/plugins/integrity-verifier.ts+++ b/v3/@claude-flow/security/src/plugins/integrity-verifier.ts@@ -129,12 +129,23 @@ export function fingerprint(publicKey: string): string {return publicKey.slice(0, 16);}+/**+ * A placeholder key that must never vouch for anything: empty or all zeros, as+ * shipped in `trust-anchors.json` until the real key is filled in. The all-zero+ * key is a small-order point: under ZIP-215 rules a fixed forged signature+ * verifies against it for every message.+ */+export function isPlaceholderKey(publicKey: string): boolean {+ return /^0*$/.test(publicKey.trim());+}+/*** Find the trust anchor that vouches for a manifest. Returns the matched* anchor (with anchor.publicKey === signer.publicKey) or null.** Scope-matching uses a minimal glob: `*` at the end of the scope string- * matches any suffix. Empty/missing scope matches every plugin id.+ * matches any suffix. Empty/missing scope matches every plugin id. Placeholder+ * anchors (see {@link isPlaceholderKey}) never match.*/export function findAnchor(anchors: ReadonlyArray<TrustAnchor>,@@ -143,6 +154,7 @@ export function findAnchor(now: number,): TrustAnchor | null {for (const a of anchors) {+ if (isPlaceholderKey(a.publicKey)) continue;if (a.publicKey !== signerPublicKey) continue;if (a.expiresAt && new Date(a.expiresAt).getTime() <= now) continue;if (!a.scope || a.scope === '*' || a.scope === pluginId) return a;@@ -224,7 +236,8 @@ export class PluginIntegrityVerifier {const sigBytes = hexToBytes(signed.signature);const msgBytes = hexToBytes(signed.manifestHash);const pubBytes = hexToBytes(signed.publicKey);- ok = await ed.verify(sigBytes, msgBytes, pubBytes);+ // RFC 8032 strict mode: rejects small-order keys, which ZIP-215 accepts.+ ok = await ed.verify(sigBytes, msgBytes, pubBytes, { zip215: false });} catch {ok = false;}@@ -251,7 +264,7 @@ function hexToBytes(hex: string): Uint8Array {}interface NobleEd25519 {- verify(sig: Uint8Array, msg: Uint8Array, pub: Uint8Array): Promise<boolean>;+ verify(sig: Uint8Array, msg: Uint8Array, pub: Uint8Array, opts?: { zip215?: boolean }): Promise<boolean>;etc: { sha512Sync?: (...m: Uint8Array[]) => Uint8Array };}