Fix swarm replies and interaction verification
This commit is contained in:
+11
-1
@@ -348,6 +348,16 @@ export default function AdminPage() {
|
|||||||
return date.toLocaleString();
|
return date.toLocaleString();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const updateStatusLabel = (() => {
|
||||||
|
if (loadingUpdateStatus) return 'Checking...';
|
||||||
|
if (!updateStatus) return 'Unavailable';
|
||||||
|
if (!updateStatus.updater.available) return updateStatus.updater.message || 'Updater unavailable';
|
||||||
|
if (updateStatus.updater.status === 'updating') return updateStatus.updater.message || 'Update in progress';
|
||||||
|
if (updateStatus.updater.status === 'error') return updateStatus.updater.message || 'Last update failed';
|
||||||
|
if (updateStatus.updateAvailable) return 'Update available';
|
||||||
|
return 'Up to date';
|
||||||
|
})();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<header style={{
|
<header style={{
|
||||||
@@ -703,7 +713,7 @@ export default function AdminPage() {
|
|||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<strong>Status:</strong>{' '}
|
<strong>Status:</strong>{' '}
|
||||||
{loadingUpdateStatus ? 'Checking…' : updateStatus?.updater.message || 'Ready'}
|
{updateStatusLabel}
|
||||||
</div>
|
</div>
|
||||||
{updateStatus?.updater.lastStartedAt && (
|
{updateStatus?.updater.lastStartedAt && (
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
@@ -117,14 +117,11 @@ export async function POST(request: Request) {
|
|||||||
.where(eq(posts.id, data.replyToId));
|
.where(eq(posts.id, data.replyToId));
|
||||||
}
|
}
|
||||||
|
|
||||||
// DEPRECATED: Push-based federation disabled
|
|
||||||
// Swarm now uses real-time pull-based federation
|
|
||||||
// Replies are fetched in real-time from the origin node
|
|
||||||
/*
|
|
||||||
if (data.swarmReplyTo) {
|
if (data.swarmReplyTo) {
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
const targetUrl = `https://${data.swarmReplyTo!.nodeDomain}/api/swarm/replies`;
|
const protocol = data.swarmReplyTo!.nodeDomain.includes('localhost') ? 'http' : 'https';
|
||||||
|
const targetUrl = `${protocol}://${data.swarmReplyTo!.nodeDomain}/api/swarm/replies`;
|
||||||
|
|
||||||
const replyPayload = {
|
const replyPayload = {
|
||||||
postId: data.swarmReplyTo!.postId,
|
postId: data.swarmReplyTo!.postId,
|
||||||
@@ -142,10 +139,17 @@ export async function POST(request: Request) {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const { createSignedPayload } = await import('@/lib/swarm/signature');
|
||||||
|
const { payload, signature } = await createSignedPayload(replyPayload);
|
||||||
|
|
||||||
const response = await fetch(targetUrl, {
|
const response = await fetch(targetUrl, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: {
|
||||||
body: JSON.stringify(replyPayload),
|
'Content-Type': 'application/json',
|
||||||
|
'X-Swarm-Source-Domain': nodeDomain,
|
||||||
|
'X-Swarm-Signature': signature,
|
||||||
|
},
|
||||||
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
@@ -158,7 +162,6 @@ export async function POST(request: Request) {
|
|||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
}
|
}
|
||||||
*/
|
|
||||||
|
|
||||||
// Handle local mentions (create notifications for users on this node)
|
// Handle local mentions (create notifications for users on this node)
|
||||||
(async () => {
|
(async () => {
|
||||||
|
|||||||
@@ -5,8 +5,10 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
|
import { db, posts } from '@/db';
|
||||||
import { fetchSwarmTimeline } from '@/lib/swarm/timeline';
|
import { fetchSwarmTimeline } from '@/lib/swarm/timeline';
|
||||||
import { getSession } from '@/lib/auth';
|
import { getSession } from '@/lib/auth';
|
||||||
|
import { and, eq, inArray, sql } from 'drizzle-orm';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* GET /api/posts/swarm
|
* GET /api/posts/swarm
|
||||||
@@ -31,9 +33,30 @@ export async function GET(request: NextRequest) {
|
|||||||
|
|
||||||
// Fetch swarm timeline (no caching - user preferences vary)
|
// Fetch swarm timeline (no caching - user preferences vary)
|
||||||
const timeline = await fetchSwarmTimeline(10, 15, { includeNsfw, cursor });
|
const timeline = await fetchSwarmTimeline(10, 15, { includeNsfw, cursor });
|
||||||
|
const swarmReplyIds = timeline.posts.map(post => `swarm:${post.nodeDomain}:${post.id}`);
|
||||||
|
const localReplyCounts = db && swarmReplyIds.length > 0
|
||||||
|
? await db.select({
|
||||||
|
swarmReplyToId: posts.swarmReplyToId,
|
||||||
|
count: sql<number>`count(*)::int`,
|
||||||
|
})
|
||||||
|
.from(posts)
|
||||||
|
.where(and(
|
||||||
|
inArray(posts.swarmReplyToId, swarmReplyIds),
|
||||||
|
eq(posts.isRemoved, false)
|
||||||
|
))
|
||||||
|
.groupBy(posts.swarmReplyToId)
|
||||||
|
: [];
|
||||||
|
const localReplyCountMap = new Map(
|
||||||
|
localReplyCounts
|
||||||
|
.filter(row => row.swarmReplyToId)
|
||||||
|
.map(row => [row.swarmReplyToId as string, row.count])
|
||||||
|
);
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
posts: timeline.posts,
|
posts: timeline.posts.map(post => ({
|
||||||
|
...post,
|
||||||
|
replyCount: post.replyCount + (localReplyCountMap.get(`swarm:${post.nodeDomain}:${post.id}`) || 0),
|
||||||
|
})),
|
||||||
sources: timeline.sources,
|
sources: timeline.sources,
|
||||||
cached: false,
|
cached: false,
|
||||||
fetchedAt: timeline.fetchedAt,
|
fetchedAt: timeline.fetchedAt,
|
||||||
|
|||||||
@@ -6,9 +6,11 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import { db, posts, users, media } from '@/db';
|
import { db, posts, users, media, notifications } from '@/db';
|
||||||
import { eq, desc, and } from 'drizzle-orm';
|
import { eq, desc, and } from 'drizzle-orm';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
import { verifySwarmRequest } from '@/lib/swarm/signature';
|
||||||
|
import { upsertRemoteUser } from '@/lib/swarm/user-cache';
|
||||||
|
|
||||||
// Schema for incoming swarm reply
|
// Schema for incoming swarm reply
|
||||||
const swarmReplySchema = z.object({
|
const swarmReplySchema = z.object({
|
||||||
@@ -19,7 +21,7 @@ const swarmReplySchema = z.object({
|
|||||||
createdAt: z.string(),
|
createdAt: z.string(),
|
||||||
author: z.object({
|
author: z.object({
|
||||||
handle: z.string(),
|
handle: z.string(),
|
||||||
displayName: z.string(),
|
displayName: z.string().optional().nullable(),
|
||||||
avatarUrl: z.string().optional(),
|
avatarUrl: z.string().optional(),
|
||||||
}),
|
}),
|
||||||
nodeDomain: z.string(),
|
nodeDomain: z.string(),
|
||||||
@@ -30,13 +32,122 @@ const swarmReplySchema = z.object({
|
|||||||
/**
|
/**
|
||||||
* POST /api/swarm/replies
|
* POST /api/swarm/replies
|
||||||
*
|
*
|
||||||
* DEPRECATED: This endpoint is disabled.
|
* Receives a signed reply from another swarm node and stores it locally
|
||||||
* We now use real-time pull-based federation instead of push-based caching.
|
* against the target post so reply counts, thread views, and notifications work.
|
||||||
*/
|
*/
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
return NextResponse.json({
|
try {
|
||||||
error: 'This endpoint is deprecated. Swarm uses real-time pull-based federation.',
|
if (!db) {
|
||||||
}, { status: 410 }); // 410 Gone
|
return NextResponse.json({ error: 'Database not available' }, { status: 503 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = await request.json();
|
||||||
|
const validation = swarmReplySchema.safeParse(body);
|
||||||
|
if (!validation.success) {
|
||||||
|
return NextResponse.json({ error: 'Invalid request', details: validation.error.issues }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const signature = request.headers.get('X-Swarm-Signature');
|
||||||
|
const sourceDomain = request.headers.get('X-Swarm-Source-Domain');
|
||||||
|
|
||||||
|
if (!signature || !sourceDomain) {
|
||||||
|
return NextResponse.json({ error: 'Missing swarm signature headers' }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = await verifySwarmRequest(validation.data, signature, sourceDomain);
|
||||||
|
if (!isValid) {
|
||||||
|
return NextResponse.json({ error: 'Invalid node signature' }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = validation.data;
|
||||||
|
if (data.reply.nodeDomain !== sourceDomain) {
|
||||||
|
return NextResponse.json({ error: 'Source domain mismatch' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parentPost = await db.query.posts.findFirst({
|
||||||
|
where: and(
|
||||||
|
eq(posts.id, data.postId),
|
||||||
|
eq(posts.isRemoved, false)
|
||||||
|
),
|
||||||
|
with: {
|
||||||
|
author: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!parentPost) {
|
||||||
|
return NextResponse.json({ error: 'Post not found' }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const remoteHandle = `${data.reply.author.handle}@${sourceDomain}`;
|
||||||
|
const remoteDid = `did:swarm:${sourceDomain}:${data.reply.author.handle}`;
|
||||||
|
|
||||||
|
await upsertRemoteUser({
|
||||||
|
handle: remoteHandle,
|
||||||
|
displayName: data.reply.author.displayName || data.reply.author.handle,
|
||||||
|
avatarUrl: data.reply.author.avatarUrl || null,
|
||||||
|
did: remoteDid,
|
||||||
|
});
|
||||||
|
|
||||||
|
const remoteUser = await db.query.users.findFirst({
|
||||||
|
where: eq(users.handle, remoteHandle),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!remoteUser) {
|
||||||
|
return NextResponse.json({ error: 'Failed to resolve remote author' }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const replyApId = `swarm:${sourceDomain}:${data.reply.id}`;
|
||||||
|
const existingReply = await db.query.posts.findFirst({
|
||||||
|
where: eq(posts.apId, replyApId),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existingReply) {
|
||||||
|
return NextResponse.json({ success: true, message: 'Reply already received' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const [createdReply] = await db.insert(posts).values({
|
||||||
|
userId: remoteUser.id,
|
||||||
|
content: data.reply.content,
|
||||||
|
replyToId: data.postId,
|
||||||
|
apId: replyApId,
|
||||||
|
apUrl: `https://${sourceDomain}/posts/${data.reply.id}`,
|
||||||
|
createdAt: new Date(data.reply.createdAt),
|
||||||
|
updatedAt: new Date(data.reply.createdAt),
|
||||||
|
}).returning();
|
||||||
|
|
||||||
|
if (data.reply.mediaUrls?.length) {
|
||||||
|
await db.insert(media).values(
|
||||||
|
data.reply.mediaUrls.map((url, index) => ({
|
||||||
|
userId: remoteUser.id,
|
||||||
|
postId: createdReply.id,
|
||||||
|
url,
|
||||||
|
altText: `Remote reply attachment ${index + 1}`,
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.update(posts)
|
||||||
|
.set({ repliesCount: parentPost.repliesCount + 1 })
|
||||||
|
.where(eq(posts.id, data.postId));
|
||||||
|
|
||||||
|
if (parentPost.userId !== remoteUser.id) {
|
||||||
|
await db.insert(notifications).values({
|
||||||
|
userId: parentPost.userId,
|
||||||
|
actorHandle: data.reply.author.handle,
|
||||||
|
actorDisplayName: data.reply.author.displayName || data.reply.author.handle,
|
||||||
|
actorAvatarUrl: data.reply.author.avatarUrl || null,
|
||||||
|
actorNodeDomain: sourceDomain,
|
||||||
|
postId: data.postId,
|
||||||
|
postContent: data.reply.content.slice(0, 200),
|
||||||
|
type: 'reply',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ success: true, message: 'Reply received' });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[Swarm] Receive reply error:', error);
|
||||||
|
return NextResponse.json({ error: 'Failed to receive reply' }, { status: 500 });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ interface NotificationPost {
|
|||||||
|
|
||||||
interface Notification {
|
interface Notification {
|
||||||
id: string;
|
id: string;
|
||||||
type: 'follow' | 'like' | 'repost' | 'mention';
|
type: 'follow' | 'like' | 'repost' | 'mention' | 'reply';
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
readAt: string | null;
|
readAt: string | null;
|
||||||
actor: NotificationActor | null;
|
actor: NotificationActor | null;
|
||||||
@@ -77,6 +77,8 @@ export default function NotificationsPage() {
|
|||||||
return 'reposted your post';
|
return 'reposted your post';
|
||||||
case 'mention':
|
case 'mention':
|
||||||
return 'mentioned you';
|
return 'mentioned you';
|
||||||
|
case 'reply':
|
||||||
|
return 'replied to your post';
|
||||||
default:
|
default:
|
||||||
return 'interacted with you';
|
return 'interacted with you';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,9 +21,7 @@ export function RightSidebar() {
|
|||||||
});
|
});
|
||||||
const [version, setVersion] = useState<{
|
const [version, setVersion] = useState<{
|
||||||
version: string;
|
version: string;
|
||||||
commit: string | null;
|
|
||||||
buildDate: string | null;
|
buildDate: string | null;
|
||||||
githubUrl: string | null;
|
|
||||||
} | null>(null);
|
} | null>(null);
|
||||||
|
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
@@ -50,7 +48,7 @@ export function RightSidebar() {
|
|||||||
fetch('/api/version')
|
fetch('/api/version')
|
||||||
.then(res => res.json())
|
.then(res => res.json())
|
||||||
.then(data => setVersion(data))
|
.then(data => setVersion(data))
|
||||||
.catch(() => setVersion({ version: 'unknown', commit: null, buildDate: null, githubUrl: null }));
|
.catch(() => setVersion({ version: 'unknown', buildDate: null }));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
@@ -123,20 +121,6 @@ export function RightSidebar() {
|
|||||||
Running{' '}
|
Running{' '}
|
||||||
<a href="https://synapsis.social" target="_blank" rel="noopener noreferrer" style={{ color: 'var(--accent)' }}>Synapsis</a>
|
<a href="https://synapsis.social" target="_blank" rel="noopener noreferrer" style={{ color: 'var(--accent)' }}>Synapsis</a>
|
||||||
{version?.version ? ` ${version.version}` : ''}
|
{version?.version ? ` ${version.version}` : ''}
|
||||||
{version?.githubUrl && version?.commit && (
|
|
||||||
<>
|
|
||||||
{' • '}
|
|
||||||
<a
|
|
||||||
href={version.githubUrl}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
title={version.commit}
|
|
||||||
style={{ color: 'var(--accent)' }}
|
|
||||||
>
|
|
||||||
{version.commit.slice(0, 7)}
|
|
||||||
</a>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
{nodeInfo.admins.length > 0 && (
|
{nodeInfo.admins.length > 0 && (
|
||||||
|
|||||||
@@ -9,28 +9,42 @@
|
|||||||
import crypto from 'crypto';
|
import crypto from 'crypto';
|
||||||
import { db, users } from '@/db';
|
import { db, users } from '@/db';
|
||||||
import { eq } from 'drizzle-orm';
|
import { eq } from 'drizzle-orm';
|
||||||
|
import { canonicalize } from '@/lib/crypto/user-signing';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sign a payload with the node's private key
|
* Sign a payload with the node's private key
|
||||||
*/
|
*/
|
||||||
export function signPayload(payload: any, privateKey: string): string {
|
export function signPayload(payload: any, privateKey: string): string {
|
||||||
const canonicalPayload = JSON.stringify(payload, Object.keys(payload).sort());
|
const canonicalPayload = canonicalize(payload);
|
||||||
const sign = crypto.createSign('SHA256');
|
const sign = crypto.createSign('SHA256');
|
||||||
sign.update(canonicalPayload);
|
sign.update(canonicalPayload);
|
||||||
sign.end();
|
sign.end();
|
||||||
return sign.sign(privateKey, 'base64');
|
return sign.sign(privateKey, 'base64');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function normalizePublicKey(publicKey: string): crypto.KeyObject | string {
|
||||||
|
if (publicKey.includes('BEGIN PUBLIC KEY')) {
|
||||||
|
return publicKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleanKey = publicKey.replace(/[\s\n\r]/g, '');
|
||||||
|
return crypto.createPublicKey({
|
||||||
|
key: Buffer.from(cleanKey, 'base64'),
|
||||||
|
format: 'der',
|
||||||
|
type: 'spki',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Verify a signature using the sender's public key
|
* Verify a signature using the sender's public key
|
||||||
*/
|
*/
|
||||||
export function verifySignature(payload: any, signature: string, publicKey: string): boolean {
|
export function verifySignature(payload: any, signature: string, publicKey: string): boolean {
|
||||||
try {
|
try {
|
||||||
const canonicalPayload = JSON.stringify(payload, Object.keys(payload).sort());
|
const canonicalPayload = canonicalize(payload);
|
||||||
const verify = crypto.createVerify('SHA256');
|
const verify = crypto.createVerify('SHA256');
|
||||||
verify.update(canonicalPayload);
|
verify.update(canonicalPayload);
|
||||||
verify.end();
|
verify.end();
|
||||||
return verify.verify(publicKey, signature, 'base64');
|
return verify.verify(normalizePublicKey(publicKey), signature, 'base64');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('[Signature] Verification failed:', error);
|
console.error('[Signature] Verification failed:', error);
|
||||||
return false;
|
return false;
|
||||||
@@ -112,7 +126,7 @@ export async function verifyUserInteraction(
|
|||||||
|
|
||||||
let publicKey: string | null = null;
|
let publicKey: string | null = null;
|
||||||
|
|
||||||
if (user?.publicKey && user.publicKey.startsWith('-----BEGIN')) {
|
if (user?.publicKey) {
|
||||||
publicKey = user.publicKey;
|
publicKey = user.publicKey;
|
||||||
} else {
|
} else {
|
||||||
// Fetch from remote node
|
// Fetch from remote node
|
||||||
|
|||||||
Reference in New Issue
Block a user