Security fixes: swarm signature verification and error handling

This commit is contained in:
Clawd Deploy Bot
2026-01-30 16:50:49 +01:00
parent 495a037eb1
commit 50355b740a
21 changed files with 850 additions and 467 deletions
+28 -6
View File
@@ -2,12 +2,15 @@
* Swarm Gossip Endpoint
*
* POST: Exchange node and handle information with other nodes
*
* SECURITY: All requests must be cryptographically signed by the sender node.
*/
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { processGossip } from '@/lib/swarm/gossip';
import { markNodeSuccess } from '@/lib/swarm/registry';
import { verifySwarmRequest } from '@/lib/swarm/signature';
import type { SwarmGossipPayload } from '@/lib/swarm/types';
const handleSchema = z.object({
@@ -38,36 +41,55 @@ const gossipPayloadSchema = z.object({
since: z.string().optional(),
});
// Schema including signature for verification
const signedGossipSchema = gossipPayloadSchema.extend({
signature: z.string(),
});
/**
* POST /api/swarm/gossip
*
* Receives gossip from another node and responds with our own data.
* This is the core of the epidemic protocol - nodes exchange what they know.
*
* SECURITY: All gossip requests must be signed by the sender node.
*/
export async function POST(request: Request) {
try {
const body = await request.json();
const payload = gossipPayloadSchema.parse(body) as SwarmGossipPayload;
const data = signedGossipSchema.parse(body);
const ourDomain = process.env.NEXT_PUBLIC_NODE_DOMAIN;
// Don't process gossip from ourselves
if (payload.sender === ourDomain) {
if (data.sender === ourDomain) {
return NextResponse.json(
{ error: 'Cannot gossip with self' },
{ status: 400 }
);
}
console.log(`[Swarm] Gossip from ${payload.sender}: ${payload.nodes.length} nodes, ${payload.handles?.length || 0} handles`);
// SECURITY: Verify the node signature before processing
const { signature, ...payload } = data;
const isValid = await verifySwarmRequest(payload, signature, data.sender);
if (!isValid) {
console.warn(`[Swarm] Invalid signature for gossip from ${data.sender}`);
return NextResponse.json(
{ error: 'Invalid signature' },
{ status: 403 }
);
}
console.log(`[Swarm] Gossip from ${data.sender}: ${data.nodes.length} nodes, ${data.handles?.length || 0} handles`);
// Process the incoming gossip and build our response
const response = await processGossip(payload);
const response = await processGossip(payload as SwarmGossipPayload);
// Mark the sender as successfully contacted
await markNodeSuccess(payload.sender);
await markNodeSuccess(data.sender);
console.log(`[Swarm] Gossip response to ${payload.sender}: ${response.nodes.length} nodes, ${response.handles?.length || 0} handles`);
console.log(`[Swarm] Gossip response to ${data.sender}: ${response.nodes.length} nodes, ${response.handles?.length || 0} handles`);
return NextResponse.json(response);
} catch (error) {