diff --git a/ruflo/src/ruvocal/docker-compose.yml b/ruflo/src/ruvocal/docker-compose.yml index f74aea158b..5f1f743d62 100644 --- a/ruflo/src/ruvocal/docker-compose.yml +++ b/ruflo/src/ruvocal/docker-compose.yml @@ -1,11 +1,12 @@ # For development only # Set MONGODB_URL=mongodb://localhost:27017 in .env.local to use this container +# The unauthenticated development database is published on host loopback only. services: mongo: image: mongo:8 hostname: mongodb ports: - - ${LOCAL_MONGO_PORT:-27017}:27017 + - "127.0.0.1:${LOCAL_MONGO_PORT:-27017}:27017" command: --replSet rs0 --bind_ip_all #--setParameter notablescan=1 mem_limit: "5g" mem_reservation: "3g" diff --git a/v3/@claude-flow/cli/README.md b/v3/@claude-flow/cli/README.md index 8382cbddbe..32111098a3 100644 --- a/v3/@claude-flow/cli/README.md +++ b/v3/@claude-flow/cli/README.md @@ -230,6 +230,12 @@ Without a token, a loopback server is still unauthenticated: any process on the --- +Startup checks report available updates without installing them. To opt in to +automatic patch installation, set `RUFLO_AUTO_UPDATE=true` (`1`, `yes` and `on` +also work). Minor and major updates remain manual; critical package priority +does not bypass an opt-out. CI detection and `CLAUDE_FLOW_AUTO_UPDATE=false` +still disable the update check. + ## What You Get | Capability | Description | diff --git a/v3/@claude-flow/cli/__tests__/startup-update-opt-in-4755.test.ts b/v3/@claude-flow/cli/__tests__/startup-update-opt-in-4755.test.ts new file mode 100644 index 0000000000..06d76b5016 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/startup-update-opt-in-4755.test.ts @@ -0,0 +1,86 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { runStartupUpdateCheck } from '../src/update/index.js'; +import { DEFAULT_CONFIG } from '../src/update/checker.js'; +import updateCommand from '../src/commands/update.js'; +import { readFileSync } from 'node:fs'; +import { parse } from 'yaml'; + +const mocks = vi.hoisted(() => ({ check: vi.fn(), execute: vi.fn() })); +vi.mock('../src/update/checker.js', () => ({ + DEFAULT_CONFIG: { enabled: true, checkIntervalHours: 24, autoUpdate: { patch: false, minor: false, major: false }, priority: {}, exclude: [] }, + checkForUpdates: mocks.check, + checkSinglePackage: vi.fn(), + getInstalledVersion: () => '1.0.0', +})); +vi.mock('../src/update/executor.js', () => ({ + executeMultipleUpdates: mocks.execute, executeUpdate: vi.fn(), rollbackUpdate: vi.fn(), + getUpdateHistory: vi.fn(), clearHistory: vi.fn(), loadHistory: vi.fn(), +})); + +beforeEach(() => { + vi.clearAllMocks(); + vi.stubEnv('RUFLO_AUTO_UPDATE', ''); + mocks.check.mockResolvedValue({ results: [{ package: '@claude-flow/cli', currentVersion: '1.0.0', latestVersion: '1.0.1', updateType: 'patch', shouldAutoUpdate: true, priority: 'critical' }], skipped: false }); + mocks.execute.mockResolvedValue([{ package: '@claude-flow/cli', version: '1.0.1', success: true }]); +}); +afterEach(() => { vi.unstubAllEnvs(); vi.restoreAllMocks(); }); + +describe('startup update installation policy', () => { + it('still reports available updates but does not install them without opt-in', async () => { + const result = await runStartupUpdateCheck({}); + expect(result.checked).toBe(true); + expect(result.updatesAvailable).toHaveLength(1); + expect(result.updatesApplied).toEqual([]); + expect(mocks.execute).not.toHaveBeenCalled(); + }); + + it.each(['1', 'true', ' YES ', 'On'])('accepts the explicit environment opt-in %s', async value => { + vi.stubEnv('RUFLO_AUTO_UPDATE', value); + expect((await runStartupUpdateCheck({})).updatesApplied).toEqual(['@claude-flow/cli@1.0.1']); + expect(mocks.check).toHaveBeenCalledWith(expect.objectContaining({ autoUpdate: { patch: true, minor: false, major: false } })); + expect(mocks.execute).toHaveBeenCalledTimes(1); + expect(DEFAULT_CONFIG.autoUpdate.patch).toBe(false); + }); + + it.each(['0', 'false', 'off', 'not-enabled'])('does not install for %s', async value => { + vi.stubEnv('RUFLO_AUTO_UPDATE', value); + expect((await runStartupUpdateCheck({})).updatesApplied).toEqual([]); + expect(mocks.execute).not.toHaveBeenCalled(); + }); + + it('lets explicit options override environment settings in both directions', async () => { + vi.stubEnv('RUFLO_AUTO_UPDATE', 'true'); + await runStartupUpdateCheck({ autoUpdate: false }); + expect(mocks.execute).not.toHaveBeenCalled(); + vi.stubEnv('RUFLO_AUTO_UPDATE', 'false'); + await runStartupUpdateCheck({ autoUpdate: true }); + expect(mocks.execute).toHaveBeenCalledTimes(1); + }); + + it('reports the same opt-in policy in update check without installing packages', async () => { + vi.stubEnv('RUFLO_AUTO_UPDATE', 'true'); + mocks.check.mockImplementation(async config => ({ + skipped: false, + results: [{ package: '@claude-flow/cli', updateType: 'patch', shouldAutoUpdate: config.autoUpdate.patch }], + })); + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + const command = updateCommand.subcommands!.find(item => item.name === 'check')!; + await command.action!({ args: [], flags: { json: true }, cwd: process.cwd(), interactive: false }); + expect(JSON.parse(log.mock.calls[0][0] as string)[0].shouldAutoUpdate).toBe(true); + expect(mocks.execute).not.toHaveBeenCalled(); + expect(DEFAULT_CONFIG.autoUpdate.patch).toBe(false); + }); + + it('keeps the CLI entry point from forcing startup installation', () => { + const source = readFileSync(new URL('../src/index.ts', import.meta.url), 'utf8'); + expect(source).not.toMatch(/runStartupUpdateCheck\(\{\s*autoUpdate:\s*true\s*\}\)/); + }); + + it('publishes the development Mongo service only on loopback', () => { + const compose = parse(readFileSync(new URL('../../../../ruflo/src/ruvocal/docker-compose.yml', import.meta.url), 'utf8')); + const ports = compose.services.mongo.ports as string[]; + expect(ports).toHaveLength(1); + const resolved = ports[0].replace('${LOCAL_MONGO_PORT:-27017}', '27118').split(':'); + expect(resolved).toEqual(['127.0.0.1', '27118', '27017']); + }); +}); diff --git a/v3/@claude-flow/cli/__tests__/update-checker-opt-in-4755.test.ts b/v3/@claude-flow/cli/__tests__/update-checker-opt-in-4755.test.ts new file mode 100644 index 0000000000..7e0078d169 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/update-checker-opt-in-4755.test.ts @@ -0,0 +1,31 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { DEFAULT_CONFIG, checkSinglePackage, checkForUpdates } from '../src/update/checker.js'; + +vi.mock('node:module', () => ({ + createRequire: () => Object.assign(() => ({ version: '1.0.0' }), { resolve: () => 'fixture-package.json' }), +})); +afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); }); + +describe('package patch updates require opt-in regardless of priority', () => { + it('disables automatic patch installation by default', () => { + expect(DEFAULT_CONFIG.autoUpdate.patch).toBe(false); + }); + + it.each(['critical', 'high', 'normal', 'low'] as const)('honors opt-out for %s packages', async priority => { + vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ 'dist-tags': { latest: '1.0.1' } }) }))); + const config = { ...DEFAULT_CONFIG, autoUpdate: { patch: false, minor: false, major: false }, priority: { '@claude-flow/cli': priority } }; + expect(await checkSinglePackage('@claude-flow/cli', config)).toMatchObject({ updateType: 'patch', shouldAutoUpdate: false }); + expect(await checkSinglePackage('@claude-flow/cli', { ...config, autoUpdate: { ...config.autoUpdate, patch: true } })).toMatchObject({ shouldAutoUpdate: true }); + }); + + it.each(['CI', 'CLAUDE_FLOW_AUTO_UPDATE'])('preserves the %s disable gate with the new opt-in present', async name => { + vi.stubEnv('CI', ''); + vi.stubEnv('CONTINUOUS_INTEGRATION', ''); + vi.stubEnv('RUFLO_AUTO_UPDATE', 'true'); + vi.stubEnv(name, name === 'CI' ? '1' : 'false'); + const fetch = vi.fn(); + vi.stubGlobal('fetch', fetch); + expect(await checkForUpdates({ ...DEFAULT_CONFIG, autoUpdate: { patch: true, minor: false, major: false } })).toMatchObject({ skipped: true, results: [] }); + expect(fetch).not.toHaveBeenCalled(); + }); +}); diff --git a/v3/@claude-flow/cli/src/commands/update.ts b/v3/@claude-flow/cli/src/commands/update.ts index 07266e3fa7..0fe2101efb 100644 --- a/v3/@claude-flow/cli/src/commands/update.ts +++ b/v3/@claude-flow/cli/src/commands/update.ts @@ -20,6 +20,7 @@ import { clearHistory, } from '../update/executor.js'; import { clearCache } from '../update/rate-limiter.js'; +import { resolveStartupUpdateConfig } from '../update/index.js'; // Helper functions function formatUpdateType(type: string): string { @@ -66,7 +67,7 @@ const checkCommand: Command = { } try { - const { results, skipped, reason } = await checkForUpdates(DEFAULT_CONFIG); + const { results, skipped, reason } = await checkForUpdates(resolveStartupUpdateConfig()); if (skipped) { output.printInfo(`Update check skipped: ${reason}`); diff --git a/v3/@claude-flow/cli/src/index.ts b/v3/@claude-flow/cli/src/index.ts index a863768e11..c7f55f0e87 100644 --- a/v3/@claude-flow/cli/src/index.ts +++ b/v3/@claude-flow/cli/src/index.ts @@ -545,7 +545,7 @@ export class CLI { */ private async checkForUpdatesOnStartup(): Promise { try { - const result = await runStartupUpdateCheck({ autoUpdate: true }); + const result = await runStartupUpdateCheck({}); // Show notifications for available updates that weren't auto-applied if (result.checked && result.updatesAvailable.length > 0) { diff --git a/v3/@claude-flow/cli/src/update/checker.ts b/v3/@claude-flow/cli/src/update/checker.ts index 055453d875..011a04ae4c 100644 --- a/v3/@claude-flow/cli/src/update/checker.ts +++ b/v3/@claude-flow/cli/src/update/checker.ts @@ -33,7 +33,7 @@ const DEFAULT_CONFIG: UpdateConfig = { enabled: true, checkIntervalHours: 24, autoUpdate: { - patch: true, + patch: false, minor: false, major: false, }, @@ -112,16 +112,10 @@ export function getUpdateType( function shouldAutoUpdate( updateType: 'major' | 'minor' | 'patch' | 'none', - priority: 'critical' | 'high' | 'normal' | 'low', config: UpdateConfig ): boolean { if (updateType === 'none') return false; - // Critical security packages always auto-update patches - if (priority === 'critical' && updateType === 'patch') { - return true; - } - // Check config if (updateType === 'major') return config.autoUpdate.major; if (updateType === 'minor') return config.autoUpdate.minor; @@ -220,7 +214,7 @@ export async function checkForUpdates( latestVersion, updateType, priority, - shouldAutoUpdate: shouldAutoUpdate(updateType, priority, config), + shouldAutoUpdate: shouldAutoUpdate(updateType, config), }); }) ); @@ -262,7 +256,7 @@ export async function checkSinglePackage( latestVersion, updateType, priority, - shouldAutoUpdate: shouldAutoUpdate(updateType, priority, config), + shouldAutoUpdate: shouldAutoUpdate(updateType, config), }; } diff --git a/v3/@claude-flow/cli/src/update/index.ts b/v3/@claude-flow/cli/src/update/index.ts index e146471ab2..9dbb44b43b 100644 --- a/v3/@claude-flow/cli/src/update/index.ts +++ b/v3/@claude-flow/cli/src/update/index.ts @@ -3,7 +3,7 @@ * * Features: * - Rate-limited update checks (24h default) - * - Automatic patch updates for security packages + * - Explicitly opted-in patch updates * - Compatibility validation before updates * - Rollback capability * - Update history logging @@ -45,10 +45,21 @@ export type { UpdateHistoryEntry, UpdateExecutionResult } from './executor.js'; // Re-export a convenience function for startup import { checkForUpdates, DEFAULT_CONFIG } from './checker.js'; -import type { UpdateCheckResult } from './checker.js'; +import type { UpdateCheckResult, UpdateConfig } from './checker.js'; import { executeMultipleUpdates } from './executor.js'; import { getInstalledVersion } from './checker.js'; +/** Resolve the same opt-in policy for startup and update diagnostics. */ +export function resolveStartupUpdateConfig(options: { autoUpdate?: boolean } = {}): UpdateConfig { + const autoUpdate = options.autoUpdate === undefined + ? /^(1|true|yes|on)$/i.test((process.env.RUFLO_AUTO_UPDATE ?? '').trim()) + : options.autoUpdate === true; + return { + ...DEFAULT_CONFIG, + autoUpdate: { ...DEFAULT_CONFIG.autoUpdate, patch: autoUpdate }, + }; +} + /** * Run auto-update check on startup * This is the main entry point for the auto-update system @@ -56,7 +67,7 @@ import { getInstalledVersion } from './checker.js'; export async function runStartupUpdateCheck(options: { verbose?: boolean; autoUpdate?: boolean; -}): Promise<{ +} = {}): Promise<{ checked: boolean; updatesAvailable: UpdateCheckResult[]; updatesApplied: string[]; @@ -70,7 +81,8 @@ export async function runStartupUpdateCheck(options: { }; try { - const { results, skipped, reason } = await checkForUpdates(DEFAULT_CONFIG); + const config = resolveStartupUpdateConfig(options); + const { results, skipped, reason } = await checkForUpdates(config); if (skipped) { result.skippedReason = reason; @@ -81,7 +93,7 @@ export async function runStartupUpdateCheck(options: { result.updatesAvailable = results; // Auto-update if enabled - if (options.autoUpdate !== false) { + if (config.autoUpdate.patch) { const autoUpdateable = results.filter((r) => r.shouldAutoUpdate); if (autoUpdateable.length > 0) { diff --git a/v3/@claude-flow/plugin-agent-federation/README.md b/v3/@claude-flow/plugin-agent-federation/README.md index e34211a276..f1879fc6e3 100644 --- a/v3/@claude-flow/plugin-agent-federation/README.md +++ b/v3/@claude-flow/plugin-agent-federation/README.md @@ -38,6 +38,12 @@ FEDERATION_TRUST_LEVEL=untrusted # default: untrusted ## Tests +Handshake signatures cover `ruflo:federation:handshake:v1:` followed by the nonce, +not the peer-supplied nonce alone. Signing adapters must sign the supplied bytes +unchanged. Both peers must use this context; raw-nonce handshake responses from +older peers are rejected, so upgrade federation peers together. This prevents a +handshake response from also verifying as a signature over bare envelope bytes. + 325 unit tests covering audit, routing, discovery, plugin lifecycle. ```bash diff --git a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/handshake-domain-4755.test.ts b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/handshake-domain-4755.test.ts new file mode 100644 index 0000000000..59ef7df3cc --- /dev/null +++ b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/handshake-domain-4755.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from 'vitest'; +import { generateKeyPairSync, sign, verify } from 'node:crypto'; +import { HandshakeService, type HandshakeChallenge } from '../../src/domain/services/handshake-service.js'; +import { FederationNode } from '../../src/domain/entities/federation-node.js'; +import { canonicalizeEnvelopeForVerify } from '../../src/application/inbound-dispatcher.js'; + +const context = 'ruflo:federation:handshake:v1:'; +const keys = generateKeyPairSync('ed25519'); +const publicKey = keys.publicKey.export({ format: 'der', type: 'spki' }).subarray(-32).toString('hex'); +const signBytes = (data: string) => sign(null, Buffer.from(data), keys.privateKey).toString('hex'); +const verifyBytes = (data: string, signature: string) => verify(null, Buffer.from(data), keys.publicKey, Buffer.from(signature, 'hex')); +const peer = () => FederationNode.create({ nodeId: 'remote', publicKey, endpoint: 'ws://remote:1', + capabilities: { agentTypes: [], maxConcurrentSessions: 1, supportedProtocols: [], complianceModes: [] } }); +const service = () => new HandshakeService({ + generateSessionId: () => 'session', generateSessionToken: () => 'token', generateNonce: () => 'nonce', + signChallenge: async data => signBytes(data), verifySignature: async (data, signature) => verifyBytes(data, signature), + pinnedKeyFor: () => publicKey, getLocalNodeId: () => 'local', getLocalPublicKey: () => publicKey, + getLocalCapabilities: () => [], +}); + +describe('handshake signature domain', () => { + it('does not sign arbitrary peer-supplied bytes as another protocol', async () => { + const nonce = canonicalizeEnvelopeForVerify({ id: 'message', type: 'task-assignment', + payload: { action: 'fixture' }, metadata: { sourceNodeId: 'remote', signatureVersion: 'jcs-v1' } }); + const challenge: HandshakeChallenge = { challengeId: 'challenge', nonce, timestamp: new Date().toISOString(), sourceNodeId: 'remote', targetNodeId: 'local' }; + const response = await service().respondToHandshake(challenge); + expect(verifyBytes(nonce, response.signedNonce)).toBe(false); + expect(verifyBytes(context + nonce, response.signedNonce)).toBe(true); + }); + + it('accepts a correctly prefixed challenge response', async () => { + const handshake = service(); + const challenge = await handshake.initiateHandshake(peer()); + const result = await handshake.verifyChallenge({ challengeId: challenge.challengeId, + signedNonce: signBytes(context + challenge.nonce), publicKey, capabilities: [] }, peer()); + expect(result.success).toBe(true); + expect(result.pinned).toBe(true); + }); + + it('rejects legacy raw-nonce and wrong-domain signatures', async () => { + for (const prefix of ['', 'different-protocol:']) { + const handshake = service(); + const challenge = await handshake.initiateHandshake(peer()); + const result = await handshake.verifyChallenge({ challengeId: challenge.challengeId, + signedNonce: signBytes(prefix + challenge.nonce), publicKey, capabilities: [] }, peer()); + expect(result).toMatchObject({ success: false, error: 'Invalid challenge signature' }); + } + }); +}); diff --git a/v3/@claude-flow/plugin-agent-federation/src/domain/services/handshake-service.ts b/v3/@claude-flow/plugin-agent-federation/src/domain/services/handshake-service.ts index 2d8e319a0a..b41f07f638 100644 --- a/v3/@claude-flow/plugin-agent-federation/src/domain/services/handshake-service.ts +++ b/v3/@claude-flow/plugin-agent-federation/src/domain/services/handshake-service.ts @@ -2,6 +2,8 @@ import { FederationNode } from '../entities/federation-node.js'; import { FederationSession, type SessionMetrics } from '../entities/federation-session.js'; import { TrustLevel } from '../entities/trust-level.js'; +export const HANDSHAKE_SIGNATURE_CONTEXT = 'ruflo:federation:handshake:v1:'; + export interface HandshakeChallenge { readonly challengeId: string; readonly nonce: string; @@ -29,8 +31,9 @@ export interface HandshakeServiceDeps { generateSessionId: () => string; generateSessionToken: () => string; generateNonce: () => string; - signChallenge: (nonce: string) => Promise; - verifySignature: (nonce: string, signature: string, publicKey: string) => Promise; + /** Sign/verify the provided domain-bound bytes without adding another prefix. */ + signChallenge: (payload: string) => Promise; + verifySignature: (payload: string, signature: string, publicKey: string) => Promise; /** The Ed25519 key (hex) the operator pinned for a node id. Without a pin, a handshake proves nothing about who answered. */ pinnedKeyFor?: (nodeId: string) => string | undefined; getLocalNodeId: () => string; @@ -83,7 +86,7 @@ export class HandshakeService { } async respondToHandshake(challenge: HandshakeChallenge): Promise { - const signedNonce = await this.deps.signChallenge(challenge.nonce); + const signedNonce = await this.deps.signChallenge(HANDSHAKE_SIGNATURE_CONTEXT + challenge.nonce); return { challengeId: challenge.challengeId, @@ -123,7 +126,7 @@ export class HandshakeService { } const isValid = await this.deps.verifySignature( - pending.challenge.nonce, + HANDSHAKE_SIGNATURE_CONTEXT + pending.challenge.nonce, response.signedNonce, response.publicKey, ); diff --git a/v3/@claude-flow/plugin-agent-federation/src/index.ts b/v3/@claude-flow/plugin-agent-federation/src/index.ts index b8067b41d7..966a5649b0 100644 --- a/v3/@claude-flow/plugin-agent-federation/src/index.ts +++ b/v3/@claude-flow/plugin-agent-federation/src/index.ts @@ -69,6 +69,7 @@ export { } from './domain/services/discovery-service.js'; export { HandshakeService, + HANDSHAKE_SIGNATURE_CONTEXT, type HandshakeChallenge, type HandshakeChallengeResponse, type HandshakeResult,