Security fixes: swarm signature verification and error handling
This commit is contained in:
@@ -2,12 +2,15 @@
|
||||
* Swarm Announce Endpoint
|
||||
*
|
||||
* POST: Receive announcements from other nodes joining the swarm
|
||||
*
|
||||
* SECURITY: All requests must be cryptographically signed by the sender node.
|
||||
*/
|
||||
|
||||
import { NextResponse } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
import { upsertSwarmNode } from '@/lib/swarm/registry';
|
||||
import { buildAnnouncement } from '@/lib/swarm/discovery';
|
||||
import { verifySwarmRequest } from '@/lib/swarm/signature';
|
||||
import type { SwarmNodeInfo } from '@/lib/swarm/types';
|
||||
|
||||
const announcementSchema = z.object({
|
||||
@@ -21,7 +24,11 @@ const announcementSchema = z.object({
|
||||
postCount: z.number().optional(),
|
||||
capabilities: z.array(z.enum(['handles', 'gossip', 'relay', 'search', 'interactions'])).optional(),
|
||||
timestamp: z.string().optional(),
|
||||
signature: z.string().optional(),
|
||||
});
|
||||
|
||||
// Schema including signature for verification
|
||||
const signedAnnouncementSchema = announcementSchema.extend({
|
||||
signature: z.string(),
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -29,39 +36,53 @@ const announcementSchema = z.object({
|
||||
*
|
||||
* Receives an announcement from another node and responds with our info.
|
||||
* This is how nodes introduce themselves to the swarm.
|
||||
*
|
||||
* SECURITY: All announcement requests must be signed by the sender node.
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const announcement = announcementSchema.parse(body);
|
||||
const data = signedAnnouncementSchema.parse(body);
|
||||
|
||||
const ourDomain = process.env.NEXT_PUBLIC_NODE_DOMAIN;
|
||||
|
||||
// Don't process announcements from ourselves
|
||||
if (announcement.domain === ourDomain) {
|
||||
if (data.domain === ourDomain) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Cannot announce to self' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// SECURITY: Verify the node signature before processing
|
||||
const { signature, ...payload } = data;
|
||||
const isValid = await verifySwarmRequest(payload, signature, data.domain);
|
||||
|
||||
if (!isValid) {
|
||||
console.warn(`[Swarm] Invalid signature for announcement from ${data.domain}`);
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid signature' },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Add/update the announcing node in our registry
|
||||
const nodeInfo: SwarmNodeInfo = {
|
||||
domain: announcement.domain,
|
||||
name: announcement.name,
|
||||
description: announcement.description,
|
||||
logoUrl: announcement.logoUrl,
|
||||
publicKey: announcement.publicKey,
|
||||
softwareVersion: announcement.softwareVersion,
|
||||
userCount: announcement.userCount,
|
||||
postCount: announcement.postCount,
|
||||
capabilities: announcement.capabilities,
|
||||
domain: data.domain,
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
logoUrl: data.logoUrl,
|
||||
publicKey: data.publicKey,
|
||||
softwareVersion: data.softwareVersion,
|
||||
userCount: data.userCount,
|
||||
postCount: data.postCount,
|
||||
capabilities: data.capabilities,
|
||||
lastSeenAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const { isNew } = await upsertSwarmNode(nodeInfo, 'announcement');
|
||||
|
||||
console.log(`[Swarm] ${isNew ? 'New' : 'Known'} node announced: ${announcement.domain}`);
|
||||
console.log(`[Swarm] ${isNew ? 'New' : 'Known'} node announced: ${data.domain}`);
|
||||
|
||||
// Respond with our own info
|
||||
const ourAnnouncement = await buildAnnouncement();
|
||||
|
||||
@@ -54,6 +54,7 @@ export async function GET(request: NextRequest) {
|
||||
handle: participant2Handle,
|
||||
displayName: participant2Handle,
|
||||
avatarUrl: null as string | null,
|
||||
did: '' as string,
|
||||
};
|
||||
|
||||
// Try to get cached user info
|
||||
@@ -103,6 +104,7 @@ export async function GET(request: NextRequest) {
|
||||
handle: cachedUser.handle,
|
||||
displayName: (cachedUser as any).displayName || cachedUser.handle,
|
||||
avatarUrl: (cachedUser as any).avatarUrl || null,
|
||||
did: (cachedUser as any).did || '',
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
'use client';
|
||||
|
||||
import { useAuth } from '@/lib/contexts/AuthContext';
|
||||
import { IdentityLockScreen } from '@/components/IdentityLockScreen';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
export default function SettingsLayout({ children }: { children: React.ReactNode }) {
|
||||
const { isIdentityUnlocked, loading } = useAuth();
|
||||
const { isIdentityUnlocked, isRestoring, loading } = useAuth();
|
||||
|
||||
if (loading) {
|
||||
// Show loading while restoring or initial load
|
||||
if (loading || isRestoring) {
|
||||
return (
|
||||
<div style={{
|
||||
minHeight: '60vh',
|
||||
@@ -21,12 +21,33 @@ export default function SettingsLayout({ children }: { children: React.ReactNode
|
||||
);
|
||||
}
|
||||
|
||||
// If not unlocked after restoration, user needs to re-login
|
||||
// (This is rare - only happens if browser was closed or session expired)
|
||||
if (!isIdentityUnlocked) {
|
||||
return (
|
||||
<IdentityLockScreen
|
||||
title="Settings Locked"
|
||||
description="To view or change your settings, you must unlock your identity. Your private keys are required to sign any changes you make."
|
||||
/>
|
||||
<div style={{
|
||||
minHeight: '60vh',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: '16px',
|
||||
padding: '24px',
|
||||
textAlign: 'center'
|
||||
}}>
|
||||
<h2 style={{ fontSize: '20px', fontWeight: 600 }}>
|
||||
Session Expired
|
||||
</h2>
|
||||
<p style={{ color: 'var(--foreground-secondary)', maxWidth: '400px' }}>
|
||||
Your session has expired. Please log out and log back in to access settings.
|
||||
</p>
|
||||
<button
|
||||
onClick={() => window.location.href = '/login'}
|
||||
className="btn btn-primary"
|
||||
>
|
||||
Go to Login
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ export default function PrivacySettingsPage() {
|
||||
const [dmPrivacy, setDmPrivacy] = useState<'everyone' | 'following' | 'none'>('everyone');
|
||||
const [status, setStatus] = useState<{ type: 'success' | 'error', message: string } | null>(null);
|
||||
|
||||
const { isIdentityUnlocked, setShowUnlockPrompt, signUserAction } = useAuth();
|
||||
const { isIdentityUnlocked, signUserAction } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/api/auth/me')
|
||||
@@ -30,9 +30,8 @@ export default function PrivacySettingsPage() {
|
||||
}, []);
|
||||
|
||||
const handleSave = async (newValue: 'everyone' | 'following' | 'none') => {
|
||||
// If identity is locked, prompt to unlock and return
|
||||
if (!isIdentityUnlocked) {
|
||||
setShowUnlockPrompt(true);
|
||||
setStatus({ type: 'error', message: 'Session expired. Please log in again.' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -55,11 +54,6 @@ export default function PrivacySettingsPage() {
|
||||
} else {
|
||||
const data = await res.json();
|
||||
setStatus({ type: 'error', message: data.error || 'Failed to save settings' });
|
||||
|
||||
// If error due to identity lock
|
||||
if (data.error === 'Invalid signature or identity') {
|
||||
setShowUnlockPrompt(true);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
setStatus({ type: 'error', message: 'An error occurred' });
|
||||
|
||||
@@ -13,7 +13,7 @@ export default function SecuritySettingsPage() {
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState<string | null>(null);
|
||||
const { isIdentityUnlocked, setShowUnlockPrompt, signUserAction } = useAuth();
|
||||
const { isIdentityUnlocked, signUserAction } = useAuth();
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
@@ -36,11 +36,9 @@ export default function SecuritySettingsPage() {
|
||||
return;
|
||||
}
|
||||
|
||||
// If identity is locked, prompt to unlock and return
|
||||
// Note: It seems redundant since they entered the password,
|
||||
// but this ensures the KEY is loaded in memory.
|
||||
// With persistence, identity should be unlocked
|
||||
if (!isIdentityUnlocked) {
|
||||
setShowUnlockPrompt(true);
|
||||
setError('Your session has expired. Please log in again.');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -60,11 +58,6 @@ export default function SecuritySettingsPage() {
|
||||
const data = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
// If error due to identity lock
|
||||
if (data.error === 'Invalid signature or identity' || data.error === 'User not found') {
|
||||
setShowUnlockPrompt(true);
|
||||
throw new Error('Identity verification failed. Please unlock your identity.');
|
||||
}
|
||||
throw new Error(data.error || 'Failed to change password');
|
||||
}
|
||||
|
||||
|
||||
@@ -79,7 +79,7 @@ export default function ProfilePage() {
|
||||
const params = useParams();
|
||||
const router = useRouter();
|
||||
const handle = (params.handle as string)?.replace(/^@/, '') || '';
|
||||
const { isIdentityUnlocked, setShowUnlockPrompt, signUserAction } = useAuth();
|
||||
const { isIdentityUnlocked, signUserAction } = useAuth();
|
||||
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [posts, setPosts] = useState<Post[]>([]);
|
||||
@@ -142,8 +142,7 @@ export default function ProfilePage() {
|
||||
|
||||
// 3. Auto-save the profile change
|
||||
if (!isIdentityUnlocked) {
|
||||
setShowUnlockPrompt(true);
|
||||
throw new Error('Please unlock your identity to save the changes.');
|
||||
throw new Error('Session expired. Please log in again.');
|
||||
}
|
||||
|
||||
// Create partial update payload
|
||||
@@ -161,11 +160,6 @@ export default function ProfilePage() {
|
||||
const saveData = await saveRes.json();
|
||||
|
||||
if (!saveRes.ok) {
|
||||
// If error due to identity lock
|
||||
if (saveData.error === 'Invalid signature or identity') {
|
||||
setShowUnlockPrompt(true);
|
||||
throw new Error('Identity verification failed. Please try again after unlocking.');
|
||||
}
|
||||
throw new Error(saveData.error || 'Failed to update profile');
|
||||
}
|
||||
|
||||
@@ -374,7 +368,7 @@ export default function ProfilePage() {
|
||||
if (!currentUser) return;
|
||||
|
||||
if (!isIdentityUnlocked) {
|
||||
setShowUnlockPrompt(true, () => handleFollow());
|
||||
alert('Session expired. Please log in again.');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -394,7 +388,7 @@ export default function ProfilePage() {
|
||||
if (!currentUser) return;
|
||||
|
||||
if (!isIdentityUnlocked) {
|
||||
setShowUnlockPrompt(true, () => handleBlock());
|
||||
alert('Session expired. Please log in again.');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -414,9 +408,8 @@ export default function ProfilePage() {
|
||||
const handleSaveProfile = async () => {
|
||||
if (!isOwnProfile) return;
|
||||
|
||||
// If identity is locked, prompt to unlock and return
|
||||
if (!isIdentityUnlocked) {
|
||||
setShowUnlockPrompt(true);
|
||||
setSaveError('Session expired. Please log in again.');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -443,14 +436,7 @@ export default function ProfilePage() {
|
||||
setIsEditing(false);
|
||||
} catch (error) {
|
||||
console.error('Profile update failed', error);
|
||||
setSaveError(error instanceof Error && error.message.includes('Identity locked')
|
||||
? 'Please unlock your identity to save changes.'
|
||||
: 'Unable to update profile. Please try again.');
|
||||
|
||||
// If the error was due to lock state (race condition), prompt unlock
|
||||
if (error instanceof Error && error.message.includes('Identity locked')) {
|
||||
setShowUnlockPrompt(true);
|
||||
}
|
||||
setSaveError(error instanceof Error ? error.message : 'Unable to update profile. Please try again.');
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
@@ -574,11 +560,7 @@ export default function ProfilePage() {
|
||||
}}
|
||||
onClick={() => {
|
||||
if (isEditing) {
|
||||
if (!isIdentityUnlocked) {
|
||||
setShowUnlockPrompt(true);
|
||||
} else {
|
||||
headerInputRef.current?.click();
|
||||
}
|
||||
headerInputRef.current?.click();
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -624,11 +606,7 @@ export default function ProfilePage() {
|
||||
}}
|
||||
onClick={() => {
|
||||
if (isEditing) {
|
||||
if (!isIdentityUnlocked) {
|
||||
setShowUnlockPrompt(true);
|
||||
} else {
|
||||
avatarInputRef.current?.click();
|
||||
}
|
||||
avatarInputRef.current?.click();
|
||||
}
|
||||
}}
|
||||
>
|
||||
|
||||
Reference in New Issue
Block a user