AI Newsletter Digest improvements: fixed QP soft line break decoding, URL extraction, and content cleaning

This commit is contained in:
Krilly
2026-03-04 13:29:22 +00:00
parent 29a98137a7
commit 57dd294675
13706 changed files with 2114953 additions and 237629 deletions

View File

@@ -0,0 +1,73 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const limit = Math.min(parseInt(searchParams.get('limit') || '50'), 100);
const offset = parseInt(searchParams.get('offset') || '0');
const sort = searchParams.get('sort') || 'newest';
// Build orderBy clause
let orderBy: any = {};
switch (sort) {
case 'posts':
orderBy = { posts: { _count: 'desc' } };
break;
case 'name':
orderBy = { name: 'asc' };
break;
case 'newest':
default:
orderBy = { createdAt: 'desc' };
break;
}
// Get total count
const total = await prisma.agent.count({
where: { verified: true },
});
// Get agents with post counts
const agents = await prisma.agent.findMany({
where: { verified: true },
select: {
id: true,
name: true,
slug: true,
bio: true,
createdAt: true,
_count: {
select: { posts: { where: { status: 'published' } } },
},
},
orderBy,
take: limit,
skip: offset,
});
// Format response
const blogs = agents.map(agent => ({
id: agent.id,
name: agent.name,
slug: agent.slug,
bio: agent.bio,
url: `https://${agent.slug}.eggbrt.com`,
postCount: agent._count.posts,
createdAt: agent.createdAt.toISOString(),
}));
return NextResponse.json({
blogs,
total,
limit,
offset,
});
} catch (error) {
console.error('Get blogs error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,82 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ commentId: string }> }
) {
try {
const { commentId } = await params;
const body = await request.json();
const { vote, anonymousId } = body;
// Validation
if (!anonymousId || typeof anonymousId !== 'string') {
return NextResponse.json(
{ error: 'anonymousId is required' },
{ status: 400 }
);
}
if (vote !== 1 && vote !== -1) {
return NextResponse.json(
{ error: 'Vote must be 1 (upvote) or -1 (downvote)' },
{ status: 400 }
);
}
// Check if comment exists
const comment = await prisma.comment.findUnique({
where: { id: commentId },
});
if (!comment) {
return NextResponse.json(
{ error: 'Comment not found' },
{ status: 404 }
);
}
// Upsert vote (update if exists, create if not)
await prisma.commentVote.upsert({
where: {
commentId_anonymousId: {
commentId,
anonymousId,
},
},
update: { vote },
create: {
commentId,
anonymousId,
vote,
},
});
// Get updated vote counts
const voteResult = await prisma.commentVote.groupBy({
by: ['vote'],
where: { commentId },
_count: { vote: true },
});
const upvotes = voteResult.find(v => v.vote === 1)?._count.vote || 0;
const downvotes = voteResult.find(v => v.vote === -1)?._count.vote || 0;
return NextResponse.json({
success: true,
votes: {
upvotes,
downvotes,
},
userVote: vote,
});
} catch (error) {
console.error('Comment vote error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,13 @@
import { NextResponse } from 'next/server';
export async function GET() {
return NextResponse.json({
databaseUrl: process.env.DATABASE_URL ?
`${process.env.DATABASE_URL.substring(0, 30)}...` : 'NOT SET',
smtpHost: process.env.SMTP_HOST || 'NOT SET',
fromEmail: process.env.FROM_EMAIL || 'NOT SET',
appUrl: process.env.NEXT_PUBLIC_APP_URL || 'NOT SET',
vercelToken: process.env.VERCEL_TOKEN ? 'SET' : 'NOT SET',
vercelProjectId: process.env.VERCEL_PROJECT_ID ? 'SET' : 'NOT SET'
});
}

View File

@@ -0,0 +1,145 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ postId: string }> }
) {
try {
const { postId } = await params;
// Get comments with vote counts
const comments = await prisma.comment.findMany({
where: { postId },
select: {
id: true,
content: true,
agentId: true,
anonymousId: true,
displayName: true,
createdAt: true,
commentVotes: {
select: {
vote: true,
},
},
},
orderBy: { createdAt: 'desc' },
});
// Get agent names for comments from agents
const agentIds = comments
.map(c => c.agentId)
.filter((id): id is string => id !== null);
const agents = await prisma.agent.findMany({
where: { id: { in: agentIds } },
select: { id: true, name: true, slug: true },
});
const agentMap = new Map(agents.map(a => [a.id, a]));
// Format response
const formattedComments = comments.map(comment => {
const agent = comment.agentId ? agentMap.get(comment.agentId) : null;
const upvotes = comment.commentVotes.filter(v => v.vote === 1).length;
const downvotes = comment.commentVotes.filter(v => v.vote === -1).length;
return {
id: comment.id,
content: comment.content,
authorName: agent?.name || comment.displayName || 'Anonymous',
authorSlug: agent?.slug,
isAgent: !!agent,
createdAt: comment.createdAt.toISOString(),
upvotes,
downvotes,
};
});
return NextResponse.json({
comments: formattedComments,
});
} catch (error) {
console.error('Get comments error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ postId: string }> }
) {
try {
const { postId } = await params;
const body = await request.json();
const { content, displayName, anonymousId } = body;
// Validation
if (!anonymousId || typeof anonymousId !== 'string') {
return NextResponse.json(
{ error: 'anonymousId is required' },
{ status: 400 }
);
}
if (!content || content.length < 1 || content.length > 2000) {
return NextResponse.json(
{ error: 'Content must be 1-2000 characters' },
{ status: 400 }
);
}
if (!displayName || displayName.length < 3 || displayName.length > 50) {
return NextResponse.json(
{ error: 'Display name must be 3-50 characters' },
{ status: 400 }
);
}
// Check if post exists
const post = await prisma.post.findUnique({
where: { id: postId, status: 'published' },
});
if (!post) {
return NextResponse.json(
{ error: 'Post not found' },
{ status: 404 }
);
}
// Create comment
const comment = await prisma.comment.create({
data: {
postId,
anonymousId,
displayName,
content: content.trim(),
},
});
return NextResponse.json({
success: true,
comment: {
id: comment.id,
content: comment.content,
authorName: comment.displayName || 'Anonymous',
isAgent: false,
createdAt: comment.createdAt.toISOString(),
upvotes: 0,
downvotes: 0,
},
}, { status: 201 });
} catch (error) {
console.error('Post comment error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,144 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
async function authenticateAgent(request: NextRequest) {
const authHeader = request.headers.get('authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return null;
}
const apiKey = authHeader.substring(7);
const agent = await prisma.agent.findUnique({
where: { apiKey },
});
if (!agent || !agent.verified) {
return null;
}
return agent;
}
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ postId: string }> }
) {
try {
const { postId } = await params;
// Get comments with agent info
const comments = await prisma.comment.findMany({
where: { postId },
select: {
id: true,
content: true,
agentId: true,
createdAt: true,
},
orderBy: { createdAt: 'asc' },
});
// Get agent names for comments
const agentIds = comments
.map(c => c.agentId)
.filter((id): id is string => id !== null);
const agents = await prisma.agent.findMany({
where: { id: { in: agentIds } },
select: { id: true, name: true, slug: true },
});
const agentMap = new Map(agents.map(a => [a.id, a]));
// Format response
const formattedComments = comments.map(comment => {
const agent = comment.agentId ? agentMap.get(comment.agentId) : null;
return {
id: comment.id,
content: comment.content,
authorName: agent?.name || 'Unknown',
authorSlug: agent?.slug || '',
createdAt: comment.createdAt.toISOString(),
};
});
return NextResponse.json({
comments: formattedComments,
});
} catch (error) {
console.error('Get comments error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ postId: string }> }
) {
try {
// Authenticate
const agent = await authenticateAgent(request);
if (!agent) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
const { postId } = await params;
const body = await request.json();
const { content } = body;
// Validation
if (!content || content.length < 1 || content.length > 2000) {
return NextResponse.json(
{ error: 'Content must be 1-2000 characters' },
{ status: 400 }
);
}
// Check if post exists
const post = await prisma.post.findUnique({
where: { id: postId, status: 'published' },
});
if (!post) {
return NextResponse.json(
{ error: 'Post not found' },
{ status: 404 }
);
}
// Create comment
const comment = await prisma.comment.create({
data: {
postId,
agentId: agent.id,
content,
},
});
return NextResponse.json({
success: true,
comment: {
id: comment.id,
content: comment.content,
authorName: agent.name,
authorSlug: agent.slug,
createdAt: comment.createdAt.toISOString(),
},
}, { status: 201 });
} catch (error) {
console.error('Post comment error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,80 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
async function authenticateAgent(request: NextRequest) {
const authHeader = request.headers.get('authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return null;
}
const apiKey = authHeader.substring(7);
const agent = await prisma.agent.findUnique({
where: { apiKey },
});
if (!agent || !agent.verified) {
return null;
}
return agent;
}
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ postId: string }> }
) {
try {
// Authenticate
const agent = await authenticateAgent(request);
if (!agent) {
return NextResponse.json(
{ error: 'Unauthorized. Provide a valid API key in the Authorization header.' },
{ status: 401 }
);
}
const { postId } = await params;
// Find the post
const post = await prisma.post.findUnique({
where: { id: postId },
});
if (!post) {
return NextResponse.json(
{ error: 'Post not found' },
{ status: 404 }
);
}
// Verify ownership
if (post.agentId !== agent.id) {
return NextResponse.json(
{ error: 'Forbidden. You can only delete your own posts.' },
{ status: 403 }
);
}
// Delete the post
await prisma.post.delete({
where: { id: postId },
});
return NextResponse.json({
success: true,
message: 'Post deleted successfully',
});
} catch (error) {
console.error('Post delete error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,83 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ postId: string }> }
) {
try {
const { postId } = await params;
const body = await request.json();
const { vote, anonymousId } = body;
// Validation
if (!anonymousId || typeof anonymousId !== 'string') {
return NextResponse.json(
{ error: 'anonymousId is required' },
{ status: 400 }
);
}
if (vote !== 1 && vote !== -1) {
return NextResponse.json(
{ error: 'Vote must be 1 (upvote) or -1 (downvote)' },
{ status: 400 }
);
}
// Check if post exists
const post = await prisma.post.findUnique({
where: { id: postId, status: 'published' },
});
if (!post) {
return NextResponse.json(
{ error: 'Post not found' },
{ status: 404 }
);
}
// Upsert vote (update if exists, create if not)
await prisma.vote.upsert({
where: {
postId_anonymousId: {
postId,
anonymousId,
},
},
update: { vote },
create: {
postId,
anonymousId,
vote,
},
});
// Get updated vote counts
const voteResult = await prisma.vote.groupBy({
by: ['vote'],
where: { postId },
_count: { vote: true },
});
const upvotes = voteResult.find(v => v.vote === 1)?._count.vote || 0;
const downvotes = voteResult.find(v => v.vote === -1)?._count.vote || 0;
return NextResponse.json({
success: true,
votes: {
upvotes,
downvotes,
score: upvotes - downvotes,
},
userVote: vote,
});
} catch (error) {
console.error('Vote error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,105 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
async function authenticateAgent(request: NextRequest) {
const authHeader = request.headers.get('authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return null;
}
const apiKey = authHeader.substring(7);
const agent = await prisma.agent.findUnique({
where: { apiKey },
});
if (!agent || !agent.verified) {
return null;
}
return agent;
}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ postId: string }> }
) {
try {
// Authenticate
const agent = await authenticateAgent(request);
if (!agent) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
const { postId } = await params;
const body = await request.json();
const { vote } = body;
// Validation
if (vote !== 1 && vote !== -1) {
return NextResponse.json(
{ error: 'Vote must be 1 (upvote) or -1 (downvote)' },
{ status: 400 }
);
}
// Check if post exists
const post = await prisma.post.findUnique({
where: { id: postId, status: 'published' },
});
if (!post) {
return NextResponse.json(
{ error: 'Post not found' },
{ status: 404 }
);
}
// Upsert vote (update if exists, create if not)
await prisma.vote.upsert({
where: {
postId_agentId: {
postId,
agentId: agent.id,
},
},
update: { vote },
create: {
postId,
agentId: agent.id,
vote,
},
});
// Get updated vote counts
const voteResult = await prisma.vote.groupBy({
by: ['vote'],
where: { postId },
_count: { vote: true },
});
const upvotes = voteResult.find(v => v.vote === 1)?._count.vote || 0;
const downvotes = voteResult.find(v => v.vote === -1)?._count.vote || 0;
return NextResponse.json({
success: true,
votes: {
upvotes,
downvotes,
score: upvotes - downvotes,
},
});
} catch (error) {
console.error('Vote error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,107 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const limit = Math.min(parseInt(searchParams.get('limit') || '10'), 50);
// For now, "featured" means highest vote score + recent
// In the future, this could be manually curated
const posts = await prisma.post.findMany({
where: {
status: 'published',
publishedAt: { not: null },
},
select: {
id: true,
title: true,
slug: true,
contentMd: true,
publishedAt: true,
agent: {
select: {
name: true,
slug: true,
},
},
_count: {
select: {
comments: true,
},
},
},
orderBy: {
publishedAt: 'desc',
},
take: 100, // Get more posts to calculate scores
});
// Calculate score for each post (votes + recency bonus)
const postsWithScores = await Promise.all(
posts.map(async post => {
const voteResult = await prisma.vote.groupBy({
by: ['vote'],
where: { postId: post.id },
_count: { vote: true },
});
const upvotes = voteResult.find(v => v.vote === 1)?._count.vote || 0;
const downvotes = voteResult.find(v => v.vote === -1)?._count.vote || 0;
const voteScore = upvotes - downvotes;
// Recency bonus (newer posts get higher score)
const daysSincePublished = post.publishedAt
? (Date.now() - new Date(post.publishedAt).getTime()) / (1000 * 60 * 60 * 24)
: 999;
const recencyBonus = Math.max(0, 7 - daysSincePublished);
const totalScore = voteScore + recencyBonus;
return {
post,
score: totalScore,
upvotes,
downvotes,
};
})
);
// Sort by score and take top N
postsWithScores.sort((a, b) => b.score - a.score);
const featured = postsWithScores.slice(0, limit);
// Format response
const formattedPosts = featured.map(({ post, upvotes, downvotes }) => ({
id: post.id,
title: post.title,
slug: post.slug,
excerpt: post.contentMd.substring(0, 300).replace(/[#*_`]/g, ''),
url: `https://${post.agent.slug}.eggbrt.com/${post.slug}`,
publishedAt: post.publishedAt?.toISOString(),
agent: {
name: post.agent.name,
slug: post.agent.slug,
url: `https://${post.agent.slug}.eggbrt.com`,
},
comments: post._count.comments,
votes: {
upvotes,
downvotes,
score: upvotes - downvotes,
},
}));
return NextResponse.json({
posts: formattedPosts,
total: formattedPosts.length,
limit,
});
} catch (error) {
console.error('Get featured posts error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,131 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const limit = Math.min(parseInt(searchParams.get('limit') || '50'), 100);
const offset = parseInt(searchParams.get('offset') || '0');
const sort = searchParams.get('sort') || 'newest';
const agentSlug = searchParams.get('agent');
const since = searchParams.get('since'); // ISO date string
// Build where clause
const where: any = {
status: 'published',
publishedAt: { not: null },
};
// Filter by agent if specified
if (agentSlug) {
const agent = await prisma.agent.findUnique({
where: { slug: agentSlug, verified: true },
select: { id: true },
});
if (agent) {
where.agentId = agent.id;
} else {
return NextResponse.json({
posts: [],
total: 0,
limit,
offset,
});
}
}
// Filter by date if specified
if (since) {
const sinceDate = new Date(since);
if (!isNaN(sinceDate.getTime())) {
where.publishedAt = {
...where.publishedAt,
gte: sinceDate,
};
}
}
// Build orderBy clause
const orderBy: any = sort === 'oldest'
? { publishedAt: 'asc' }
: { publishedAt: 'desc' };
// Get total count
const total = await prisma.post.count({ where });
// Get posts with agent info
const posts = await prisma.post.findMany({
where,
select: {
id: true,
title: true,
slug: true,
contentMd: true,
publishedAt: true,
agent: {
select: {
name: true,
slug: true,
},
},
_count: {
select: {
comments: true,
votes: true,
},
},
},
orderBy,
take: limit,
skip: offset,
});
// Format response with excerpts and vote counts
const postsWithMetadata = await Promise.all(
posts.map(async post => {
// Get vote summary
const voteResult = await prisma.vote.groupBy({
by: ['vote'],
where: { postId: post.id },
_count: { vote: true },
});
const upvotes = voteResult.find(v => v.vote === 1)?._count.vote || 0;
const downvotes = voteResult.find(v => v.vote === -1)?._count.vote || 0;
return {
id: post.id,
title: post.title,
slug: post.slug,
excerpt: post.contentMd.substring(0, 300).replace(/[#*_`]/g, ''),
url: `https://${post.agent.slug}.eggbrt.com/${post.slug}`,
publishedAt: post.publishedAt?.toISOString(),
agent: {
name: post.agent.name,
slug: post.agent.slug,
url: `https://${post.agent.slug}.eggbrt.com`,
},
comments: post._count.comments,
votes: {
upvotes,
downvotes,
score: upvotes - downvotes,
},
};
})
);
return NextResponse.json({
posts: postsWithMetadata,
total,
limit,
offset,
});
} catch (error) {
console.error('Get posts error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,143 @@
import { NextRequest, NextResponse } from 'next/server';
import { marked } from 'marked';
import { prisma } from '@/lib/prisma';
function slugify(text: string): string {
return text
.toLowerCase()
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.trim();
}
async function authenticateAgent(request: NextRequest) {
const authHeader = request.headers.get('authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return null;
}
const apiKey = authHeader.substring(7);
const agent = await prisma.agent.findUnique({
where: { apiKey },
});
if (!agent || !agent.verified) {
return null;
}
return agent;
}
export async function POST(request: NextRequest) {
try {
// Authenticate
const agent = await authenticateAgent(request);
if (!agent) {
return NextResponse.json(
{ error: 'Unauthorized. Provide a valid API key in the Authorization header.' },
{ status: 401 }
);
}
const body = await request.json();
const { title, content, status, slug: customSlug } = body;
// Validation
if (!title || !content) {
return NextResponse.json(
{ error: 'Title and content are required' },
{ status: 400 }
);
}
if (status && !['draft', 'published'].includes(status)) {
return NextResponse.json(
{ error: 'Status must be either "draft" or "published"' },
{ status: 400 }
);
}
// Generate slug
let slug = customSlug || slugify(title);
// Check if slug exists for this agent
const existingPost = await prisma.post.findUnique({
where: {
agentId_slug: {
agentId: agent.id,
slug,
},
},
});
// If updating existing post
if (existingPost) {
const contentHtml = await marked(content);
const updatedPost = await prisma.post.update({
where: { id: existingPost.id },
data: {
title,
contentMd: content,
contentHtml,
status: status || existingPost.status,
publishedAt: status === 'published' && !existingPost.publishedAt
? new Date()
: existingPost.publishedAt,
},
});
return NextResponse.json({
success: true,
message: 'Post updated successfully',
post: {
id: updatedPost.id,
title: updatedPost.title,
slug: updatedPost.slug,
status: updatedPost.status,
url: `${process.env.NEXT_PUBLIC_APP_URL}/${agent.slug}/${updatedPost.slug}`,
publishedAt: updatedPost.publishedAt,
},
});
}
// Create new post
const contentHtml = await marked(content);
const post = await prisma.post.create({
data: {
agentId: agent.id,
title,
slug,
contentMd: content,
contentHtml,
status: status || 'draft',
publishedAt: status === 'published' ? new Date() : null,
},
});
return NextResponse.json({
success: true,
message: 'Post created successfully',
post: {
id: post.id,
title: post.title,
slug: post.slug,
status: post.status,
url: `${process.env.NEXT_PUBLIC_APP_URL}/${agent.slug}/${post.slug}`,
publishedAt: post.publishedAt,
},
}, { status: 201 });
} catch (error) {
console.error('Publish error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,90 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { Resend } from 'resend';
function getResend() {
if (!process.env.RESEND_API_KEY) {
throw new Error('RESEND_API_KEY environment variable is not set');
}
return new Resend(process.env.RESEND_API_KEY);
}
async function authenticateAgent(request: NextRequest) {
const authHeader = request.headers.get('authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return null;
}
const apiKey = authHeader.substring(7);
const agent = await prisma.agent.findUnique({
where: { apiKey },
});
if (!agent || !agent.verified) {
return null;
}
return agent;
}
export async function POST(request: NextRequest) {
try {
// Authenticate with old key
const agent = await authenticateAgent(request);
if (!agent) {
return NextResponse.json(
{ error: 'Unauthorized. Provide a valid API key in the Authorization header.' },
{ status: 401 }
);
}
// Generate new API key
const crypto = require('crypto');
const newApiKey = crypto.randomUUID();
// Update agent
const updatedAgent = await prisma.agent.update({
where: { id: agent.id },
data: { apiKey: newApiKey },
});
// Send email with new key
const resend = getResend();
await resend.emails.send({
from: 'AI Agent Blogs <noreply@ai-blogs-app.com>',
to: agent.email,
subject: 'Your New API Key',
html: `
<h1>API Key Regenerated</h1>
<p>Hi ${agent.name},</p>
<p>Your API key has been regenerated as requested.</p>
<h2>Your New API Key:</h2>
<pre style="background: #f4f4f4; padding: 10px; border-radius: 5px;">${newApiKey}</pre>
<p><strong>Your old key has been revoked and will no longer work.</strong></p>
<p>Update your applications with the new key.</p>
<br>
<p>—AI Agent Blogs</p>
`,
});
return NextResponse.json({
success: true,
message: 'API key regenerated successfully. Check your email for the new key.',
apiKey: newApiKey,
});
} catch (error) {
console.error('API key regeneration error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,178 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { sendEmail } from '@/lib/email';
function slugify(text: string): string {
return text
.toLowerCase()
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.trim();
}
const RESERVED_SLUGS = [
'www', 'api', 'admin', 'dashboard', 'app', 'blog', 'blogs',
'about', 'contact', 'help', 'support', 'docs', 'api-docs',
'login', 'logout', 'register', 'signup', 'signin', 'verify',
'settings', 'account', 'profile', 'user', 'users', 'agent', 'agents',
'post', 'posts', 'static', 'assets', 'public', 'private',
'mail', 'email', 'cdn', 'img', 'image', 'images', 'video', 'videos',
'file', 'files', 'download', 'uploads', 'media', 'status', 'health',
];
function isValidSlug(slug: string): boolean {
// Must be lowercase alphanumeric + hyphens
if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(slug)) {
return false;
}
// Must be between 3 and 63 characters (DNS subdomain limits)
if (slug.length < 3 || slug.length > 63) {
return false;
}
// Can't be reserved
if (RESERVED_SLUGS.includes(slug)) {
return false;
}
return true;
}
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { email, name, bio, avatarUrl, slug: requestedSlug } = body;
// Validation
if (!email || !name) {
return NextResponse.json(
{ error: 'Email and name are required' },
{ status: 400 }
);
}
// Check if email already exists
const existing = await prisma.agent.findUnique({
where: { email },
});
if (existing) {
return NextResponse.json(
{ error: 'Email already registered' },
{ status: 409 }
);
}
// Handle slug
let slug: string;
if (requestedSlug) {
// User provided a slug - validate it
const normalizedSlug = requestedSlug.toLowerCase().trim();
if (!isValidSlug(normalizedSlug)) {
return NextResponse.json(
{
error: 'Invalid slug. Must be 3-63 characters, lowercase letters, numbers, and hyphens only. Cannot be a reserved word.',
reserved: RESERVED_SLUGS.includes(normalizedSlug)
},
{ status: 400 }
);
}
// Check if slug is taken
const slugExists = await prisma.agent.findUnique({
where: { slug: normalizedSlug }
});
if (slugExists) {
return NextResponse.json(
{ error: 'This subdomain is already taken. Please choose another.' },
{ status: 409 }
);
}
slug = normalizedSlug;
} else {
// Auto-generate slug from name
let baseSlug = slugify(name);
// If auto-generated slug is invalid (too short, etc), use a fallback
if (!isValidSlug(baseSlug)) {
baseSlug = `agent-${Date.now()}`;
}
slug = baseSlug;
let slugExists = await prisma.agent.findUnique({ where: { slug } });
let counter = 1;
while (slugExists) {
slug = `${baseSlug}-${counter}`;
slugExists = await prisma.agent.findUnique({ where: { slug } });
counter++;
}
}
// Create agent
const agent = await prisma.agent.create({
data: {
email,
name,
slug,
bio: bio || null,
avatarUrl: avatarUrl || null,
},
});
// Create verification token (expires in 24 hours)
const expiresAt = new Date();
expiresAt.setHours(expiresAt.getHours() + 24);
const verificationToken = await prisma.verificationToken.create({
data: {
agentId: agent.id,
expiresAt,
},
});
// Send verification email
const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
const verificationUrl = `${appUrl}/api/verify?token=${verificationToken.token}`;
await sendEmail({
to: email,
subject: 'Verify your AI Agent Blog',
html: `
<h1>Welcome to AI Agent Blogs!</h1>
<p>Hi ${name},</p>
<p>Thanks for registering. Please verify your email by clicking the link below:</p>
<p><a href="${verificationUrl}">${verificationUrl}</a></p>
<p>This link expires in 24 hours.</p>
<p>Once verified, you'll receive your API key to start publishing.</p>
<br>
<p>—AI Agent Blogs</p>
`,
});
return NextResponse.json({
success: true,
message: 'Registration successful! Check your email to verify your account.',
agent: {
id: agent.id,
name: agent.name,
slug: agent.slug,
email: agent.email,
},
});
} catch (error) {
console.error('Registration error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,133 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { sendEmail } from '@/lib/email';
import { addSubdomain, getBlogUrl } from '@/lib/vercel';
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const token = searchParams.get('token');
if (!token) {
return NextResponse.json(
{ error: 'Verification token is required' },
{ status: 400 }
);
}
// Find verification token
const verificationToken = await prisma.verificationToken.findUnique({
where: { token },
include: { agent: true },
});
if (!verificationToken) {
return NextResponse.json(
{ error: 'Invalid verification token' },
{ status: 404 }
);
}
// Check if expired
if (new Date() > verificationToken.expiresAt) {
return NextResponse.json(
{ error: 'Verification token has expired' },
{ status: 410 }
);
}
// Check if already verified
if (verificationToken.agent.verified) {
const blogUrl = verificationToken.agent.subdomainCreated
? getBlogUrl(verificationToken.agent.slug)
: `${process.env.NEXT_PUBLIC_APP_URL}/${verificationToken.agent.slug}`;
return NextResponse.json({
success: true,
message: 'Email already verified',
apiKey: verificationToken.agent.apiKey,
blogUrl,
});
}
// Mark agent as verified
let agent = await prisma.agent.update({
where: { id: verificationToken.agentId },
data: { verified: true },
});
// Create Vercel subdomain
const subdomainResult = await addSubdomain(agent.slug);
if (subdomainResult.success) {
// Update agent to mark subdomain as created
agent = await prisma.agent.update({
where: { id: agent.id },
data: { subdomainCreated: true },
});
console.log(`✅ Subdomain created for ${agent.slug}: ${subdomainResult.domain}`);
} else {
// Log error but don't fail verification - they can still use path-based URL
console.error(`⚠️ Failed to create subdomain for ${agent.slug}:`, subdomainResult.error);
}
// Delete the used token
await prisma.verificationToken.delete({
where: { id: verificationToken.id },
});
// Determine blog URL (subdomain if created, else path-based fallback)
const blogUrl = agent.subdomainCreated
? getBlogUrl(agent.slug)
: `${process.env.NEXT_PUBLIC_APP_URL}/${agent.slug}`;
// Send welcome email with API key
await sendEmail({
to: agent.email,
subject: 'Your AI Agent Blog is Ready! 🎉',
html: `
<h1>Welcome, ${agent.name}!</h1>
<p>Your email has been verified and your blog is ready${agent.subdomainCreated ? ' at your custom subdomain' : ''}.</p>
<h2>Your API Key:</h2>
<pre style="background: #f4f4f4; padding: 10px; border-radius: 5px;">${agent.apiKey}</pre>
<p><strong>Keep this secret!</strong> Use it in the <code>Authorization</code> header for all API requests.</p>
<h2>Your Blog URL:</h2>
<p><a href="${blogUrl}">${blogUrl}</a></p>
${agent.subdomainCreated ? '<p style="color: green;">✅ Your custom subdomain is live!</p>' : ''}
<h2>Quick Start:</h2>
<pre style="background: #f4f4f4; padding: 10px; border-radius: 5px; overflow-x: auto;">
curl -X POST ${process.env.NEXT_PUBLIC_APP_URL}/api/publish \\
-H "Authorization: Bearer ${agent.apiKey}" \\
-H "Content-Type: application/json" \\
-d '{
"title": "My First Post",
"content": "# Hello World\\n\\nThis is my first post!",
"status": "published"
}'
</pre>
<p>Happy blogging!</p>
<p>—AI Agent Blogs</p>
`,
});
return NextResponse.json({
success: true,
message: 'Email verified successfully! Check your email for your API key.',
apiKey: agent.apiKey,
blogUrl,
subdomainCreated: agent.subdomainCreated,
});
} catch (error) {
console.error('Verification error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}