Initial commit

This commit is contained in:
root
2026-01-26 08:34:48 +01:00
commit 387314581f
216 changed files with 81204 additions and 0 deletions
@@ -0,0 +1,126 @@
/**
* Swarm Follow Endpoint
*
* POST: Receive a follow from another swarm node
*
* This enables swarm-native follows between Synapsis nodes,
* bypassing ActivityPub for faster, more direct connections.
*/
import { NextRequest, NextResponse } from 'next/server';
import { db, users, notifications, remoteFollowers } from '@/db';
import { eq, and } from 'drizzle-orm';
import { z } from 'zod';
const swarmFollowSchema = z.object({
targetHandle: z.string(),
follow: z.object({
followerHandle: z.string(),
followerDisplayName: z.string(),
followerAvatarUrl: z.string().optional(),
followerBio: z.string().optional(),
followerNodeDomain: z.string(),
interactionId: z.string(),
timestamp: z.string(),
}),
});
/**
* POST /api/swarm/interactions/follow
*
* Receives a follow from another swarm node.
*/
export async function POST(request: NextRequest) {
try {
if (!db) {
return NextResponse.json({ error: 'Database not available' }, { status: 503 });
}
const body = await request.json();
const data = swarmFollowSchema.parse(body);
// Find the target user (local user being followed)
const targetUser = await db.query.users.findFirst({
where: eq(users.handle, data.targetHandle.toLowerCase()),
});
if (!targetUser) {
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}
if (targetUser.isSuspended) {
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}
// Construct the remote follower's actor URL (swarm-style)
const remoteHandle = `${data.follow.followerHandle}@${data.follow.followerNodeDomain}`;
const actorUrl = `swarm://${data.follow.followerNodeDomain}/${data.follow.followerHandle}`;
const inboxUrl = `https://${data.follow.followerNodeDomain}/api/swarm/interactions/inbox`;
// Check if this follow already exists
const existingFollow = await db.query.remoteFollowers.findFirst({
where: and(
eq(remoteFollowers.userId, targetUser.id),
eq(remoteFollowers.actorUrl, actorUrl)
),
});
if (existingFollow) {
return NextResponse.json({
success: true,
message: 'Already following',
});
}
// Create the remote follower record
await db.insert(remoteFollowers).values({
userId: targetUser.id,
actorUrl,
inboxUrl,
handle: remoteHandle,
activityId: data.follow.interactionId,
});
// Update follower count
await db.update(users)
.set({ followersCount: targetUser.followersCount + 1 })
.where(eq(users.id, targetUser.id));
// Get or create placeholder user for the remote follower (for notifications)
let remoteUser = await db.query.users.findFirst({
where: eq(users.handle, remoteHandle),
});
if (!remoteUser) {
const [newUser] = await db.insert(users).values({
did: `did:swarm:${data.follow.followerNodeDomain}:${data.follow.followerHandle}`,
handle: remoteHandle,
displayName: data.follow.followerDisplayName,
avatarUrl: data.follow.followerAvatarUrl || null,
bio: data.follow.followerBio || null,
publicKey: 'swarm-remote-user',
}).returning();
remoteUser = newUser;
}
// Create notification
await db.insert(notifications).values({
userId: targetUser.id,
actorId: remoteUser.id,
type: 'follow',
});
console.log(`[Swarm] Received follow from ${remoteHandle} for @${data.targetHandle}`);
return NextResponse.json({
success: true,
message: 'Follow received',
});
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json({ error: 'Invalid request', details: error.issues }, { status: 400 });
}
console.error('[Swarm] Follow error:', error);
return NextResponse.json({ error: 'Failed to process follow' }, { status: 500 });
}
}
@@ -0,0 +1,100 @@
/**
* Swarm Like Endpoint
*
* POST: Receive a like from another swarm node
*
* This is the swarm-first approach - direct node-to-node communication
* for likes, bypassing ActivityPub for Synapsis nodes.
*/
import { NextRequest, NextResponse } from 'next/server';
import { db, posts, users, notifications } from '@/db';
import { eq } from 'drizzle-orm';
import { z } from 'zod';
const swarmLikeSchema = z.object({
postId: z.string().uuid(),
like: z.object({
actorHandle: z.string(),
actorDisplayName: z.string(),
actorAvatarUrl: z.string().optional(),
actorNodeDomain: z.string(),
interactionId: z.string(),
timestamp: z.string(),
}),
});
/**
* POST /api/swarm/interactions/like
*
* Receives a like from another swarm node.
*/
export async function POST(request: NextRequest) {
try {
if (!db) {
return NextResponse.json({ error: 'Database not available' }, { status: 503 });
}
const body = await request.json();
const data = swarmLikeSchema.parse(body);
// Find the target post
const post = await db.query.posts.findFirst({
where: eq(posts.id, data.postId),
with: { author: true },
});
if (!post) {
return NextResponse.json({ error: 'Post not found' }, { status: 404 });
}
if (post.isRemoved) {
return NextResponse.json({ error: 'Post not found' }, { status: 404 });
}
// Increment like count
await db.update(posts)
.set({ likesCount: post.likesCount + 1 })
.where(eq(posts.id, data.postId));
// Create a notification for the post author
// First, get or create a placeholder user for the remote liker
const remoteHandle = `${data.like.actorHandle}@${data.like.actorNodeDomain}`;
let remoteUser = await db.query.users.findFirst({
where: eq(users.handle, remoteHandle),
});
if (!remoteUser) {
// Create a placeholder user for the remote actor
const [newUser] = await db.insert(users).values({
did: `did:swarm:${data.like.actorNodeDomain}:${data.like.actorHandle}`,
handle: remoteHandle,
displayName: data.like.actorDisplayName,
avatarUrl: data.like.actorAvatarUrl || null,
publicKey: 'swarm-remote-user',
}).returning();
remoteUser = newUser;
}
// Create notification
await db.insert(notifications).values({
userId: post.userId,
actorId: remoteUser.id,
postId: data.postId,
type: 'like',
});
console.log(`[Swarm] Received like from ${remoteHandle} on post ${data.postId}`);
return NextResponse.json({
success: true,
message: 'Like received',
});
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json({ error: 'Invalid request', details: error.issues }, { status: 400 });
}
console.error('[Swarm] Like error:', error);
return NextResponse.json({ error: 'Failed to process like' }, { status: 500 });
}
}
@@ -0,0 +1,110 @@
/**
* Swarm Mention Endpoint
*
* POST: Receive a mention notification from another swarm node
*/
import { NextRequest, NextResponse } from 'next/server';
import { db, users, notifications, posts } from '@/db';
import { eq } from 'drizzle-orm';
import { z } from 'zod';
const swarmMentionSchema = z.object({
mentionedHandle: z.string(),
mention: z.object({
actorHandle: z.string(),
actorDisplayName: z.string(),
actorAvatarUrl: z.string().optional(),
actorNodeDomain: z.string(),
postId: z.string(),
postContent: z.string(),
interactionId: z.string(),
timestamp: z.string(),
}),
});
/**
* POST /api/swarm/interactions/mention
*
* Receives a mention notification from another swarm node.
*/
export async function POST(request: NextRequest) {
try {
if (!db) {
return NextResponse.json({ error: 'Database not available' }, { status: 503 });
}
const body = await request.json();
const data = swarmMentionSchema.parse(body);
// Find the mentioned user (local user)
const mentionedUser = await db.query.users.findFirst({
where: eq(users.handle, data.mentionedHandle.toLowerCase()),
});
if (!mentionedUser) {
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}
if (mentionedUser.isSuspended) {
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}
// Get or create placeholder user for the remote actor
const remoteHandle = `${data.mention.actorHandle}@${data.mention.actorNodeDomain}`;
let remoteUser = await db.query.users.findFirst({
where: eq(users.handle, remoteHandle),
});
if (!remoteUser) {
const [newUser] = await db.insert(users).values({
did: `did:swarm:${data.mention.actorNodeDomain}:${data.mention.actorHandle}`,
handle: remoteHandle,
displayName: data.mention.actorDisplayName,
avatarUrl: data.mention.actorAvatarUrl || null,
publicKey: 'swarm-remote-user',
}).returning();
remoteUser = newUser;
}
// Check if we already have this post cached (from swarm timeline)
// If not, create a placeholder post for the notification
const swarmPostId = `swarm:${data.mention.actorNodeDomain}:${data.mention.postId}`;
let post = await db.query.posts.findFirst({
where: eq(posts.apId, swarmPostId),
});
if (!post) {
// Create a placeholder post for the mention
const [newPost] = await db.insert(posts).values({
userId: remoteUser.id,
content: data.mention.postContent,
apId: swarmPostId,
apUrl: `https://${data.mention.actorNodeDomain}/${data.mention.actorHandle}/posts/${data.mention.postId}`,
createdAt: new Date(data.mention.timestamp),
}).returning();
post = newPost;
}
// Create notification
await db.insert(notifications).values({
userId: mentionedUser.id,
actorId: remoteUser.id,
postId: post.id,
type: 'mention',
});
console.log(`[Swarm] Received mention from ${remoteHandle} for @${data.mentionedHandle}`);
return NextResponse.json({
success: true,
message: 'Mention received',
});
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json({ error: 'Invalid request', details: error.issues }, { status: 400 });
}
console.error('[Swarm] Mention error:', error);
return NextResponse.json({ error: 'Failed to process mention' }, { status: 500 });
}
}
@@ -0,0 +1,95 @@
/**
* Swarm Repost Endpoint
*
* POST: Receive a repost from another swarm node
*/
import { NextRequest, NextResponse } from 'next/server';
import { db, posts, users, notifications } from '@/db';
import { eq } from 'drizzle-orm';
import { z } from 'zod';
const swarmRepostSchema = z.object({
postId: z.string().uuid(),
repost: z.object({
actorHandle: z.string(),
actorDisplayName: z.string(),
actorAvatarUrl: z.string().optional(),
actorNodeDomain: z.string(),
repostId: z.string(), // The ID of the repost on the actor's node
interactionId: z.string(),
timestamp: z.string(),
}),
});
/**
* POST /api/swarm/interactions/repost
*
* Receives a repost notification from another swarm node.
*/
export async function POST(request: NextRequest) {
try {
if (!db) {
return NextResponse.json({ error: 'Database not available' }, { status: 503 });
}
const body = await request.json();
const data = swarmRepostSchema.parse(body);
// Find the target post
const post = await db.query.posts.findFirst({
where: eq(posts.id, data.postId),
});
if (!post) {
return NextResponse.json({ error: 'Post not found' }, { status: 404 });
}
if (post.isRemoved) {
return NextResponse.json({ error: 'Post not found' }, { status: 404 });
}
// Increment repost count
await db.update(posts)
.set({ repostsCount: post.repostsCount + 1 })
.where(eq(posts.id, data.postId));
// Get or create placeholder user for the remote reposter
const remoteHandle = `${data.repost.actorHandle}@${data.repost.actorNodeDomain}`;
let remoteUser = await db.query.users.findFirst({
where: eq(users.handle, remoteHandle),
});
if (!remoteUser) {
const [newUser] = await db.insert(users).values({
did: `did:swarm:${data.repost.actorNodeDomain}:${data.repost.actorHandle}`,
handle: remoteHandle,
displayName: data.repost.actorDisplayName,
avatarUrl: data.repost.actorAvatarUrl || null,
publicKey: 'swarm-remote-user',
}).returning();
remoteUser = newUser;
}
// Create notification
await db.insert(notifications).values({
userId: post.userId,
actorId: remoteUser.id,
postId: data.postId,
type: 'repost',
});
console.log(`[Swarm] Received repost from ${remoteHandle} on post ${data.postId}`);
return NextResponse.json({
success: true,
message: 'Repost received',
});
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json({ error: 'Invalid request', details: error.issues }, { status: 400 });
}
console.error('[Swarm] Repost error:', error);
return NextResponse.json({ error: 'Failed to process repost' }, { status: 500 });
}
}
@@ -0,0 +1,83 @@
/**
* Swarm Unfollow Endpoint
*
* POST: Receive an unfollow from another swarm node
*/
import { NextRequest, NextResponse } from 'next/server';
import { db, users, remoteFollowers } from '@/db';
import { eq, and } from 'drizzle-orm';
import { z } from 'zod';
const swarmUnfollowSchema = z.object({
targetHandle: z.string(),
unfollow: z.object({
followerHandle: z.string(),
followerNodeDomain: z.string(),
interactionId: z.string(),
timestamp: z.string(),
}),
});
/**
* POST /api/swarm/interactions/unfollow
*
* Receives an unfollow from another swarm node.
*/
export async function POST(request: NextRequest) {
try {
if (!db) {
return NextResponse.json({ error: 'Database not available' }, { status: 503 });
}
const body = await request.json();
const data = swarmUnfollowSchema.parse(body);
// Find the target user
const targetUser = await db.query.users.findFirst({
where: eq(users.handle, data.targetHandle.toLowerCase()),
});
if (!targetUser) {
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}
// Find and remove the remote follower record
const actorUrl = `swarm://${data.unfollow.followerNodeDomain}/${data.unfollow.followerHandle}`;
const existingFollow = await db.query.remoteFollowers.findFirst({
where: and(
eq(remoteFollowers.userId, targetUser.id),
eq(remoteFollowers.actorUrl, actorUrl)
),
});
if (!existingFollow) {
return NextResponse.json({
success: true,
message: 'Not following',
});
}
// Remove the follow
await db.delete(remoteFollowers).where(eq(remoteFollowers.id, existingFollow.id));
// Update follower count
await db.update(users)
.set({ followersCount: Math.max(0, targetUser.followersCount - 1) })
.where(eq(users.id, targetUser.id));
console.log(`[Swarm] Received unfollow from ${data.unfollow.followerHandle}@${data.unfollow.followerNodeDomain} for @${data.targetHandle}`);
return NextResponse.json({
success: true,
message: 'Unfollow received',
});
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json({ error: 'Invalid request', details: error.issues }, { status: 400 });
}
console.error('[Swarm] Unfollow error:', error);
return NextResponse.json({ error: 'Failed to process unfollow' }, { status: 500 });
}
}
@@ -0,0 +1,63 @@
/**
* Swarm Unlike Endpoint
*
* POST: Receive an unlike from another swarm node
*/
import { NextRequest, NextResponse } from 'next/server';
import { db, posts } from '@/db';
import { eq } from 'drizzle-orm';
import { z } from 'zod';
const swarmUnlikeSchema = z.object({
postId: z.string().uuid(),
unlike: z.object({
actorHandle: z.string(),
actorNodeDomain: z.string(),
interactionId: z.string(),
timestamp: z.string(),
}),
});
/**
* POST /api/swarm/interactions/unlike
*
* Receives an unlike from another swarm node.
*/
export async function POST(request: NextRequest) {
try {
if (!db) {
return NextResponse.json({ error: 'Database not available' }, { status: 503 });
}
const body = await request.json();
const data = swarmUnlikeSchema.parse(body);
// Find the target post
const post = await db.query.posts.findFirst({
where: eq(posts.id, data.postId),
});
if (!post) {
return NextResponse.json({ error: 'Post not found' }, { status: 404 });
}
// Decrement like count (don't go below 0)
await db.update(posts)
.set({ likesCount: Math.max(0, post.likesCount - 1) })
.where(eq(posts.id, data.postId));
console.log(`[Swarm] Received unlike from ${data.unlike.actorHandle}@${data.unlike.actorNodeDomain} on post ${data.postId}`);
return NextResponse.json({
success: true,
message: 'Unlike received',
});
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json({ error: 'Invalid request', details: error.issues }, { status: 400 });
}
console.error('[Swarm] Unlike error:', error);
return NextResponse.json({ error: 'Failed to process unlike' }, { status: 500 });
}
}