Add chat page, improve chat API, and remove ChatWidget
Introduces a new chat page with end-to-end encryption, conversation list, and message thread UI. Adds new API endpoints for unread message count and debugging chat keys/messages. Improves chat key validation and reciprocal conversation/message creation for local recipients. Removes the old ChatWidget component. Updates login and chat API logic for better Turnstile and key handling.
This commit is contained in:
@@ -6,7 +6,7 @@ import { z } from 'zod';
|
||||
const loginSchema = z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string(),
|
||||
turnstileToken: z.string().optional(),
|
||||
turnstileToken: z.string().optional().nullable(),
|
||||
});
|
||||
|
||||
export async function POST(request: Request) {
|
||||
@@ -14,7 +14,7 @@ export async function POST(request: Request) {
|
||||
const body = await request.json();
|
||||
const data = loginSchema.parse(body);
|
||||
|
||||
// Verify Turnstile token if provided
|
||||
// Verify Turnstile token only if it's provided (meaning Turnstile is enabled)
|
||||
if (data.turnstileToken) {
|
||||
const ip = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || undefined;
|
||||
const isValid = await verifyTurnstileToken(data.turnstileToken, ip);
|
||||
|
||||
@@ -53,9 +53,26 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json({ error: 'chatPublicKey required' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Validate it looks like a base64 SPKI key
|
||||
if (chatPublicKey.length < 50 || chatPublicKey.length > 500) {
|
||||
return NextResponse.json({ error: 'Invalid public key format' }, { status: 400 });
|
||||
// Validate it looks like a base64 SPKI key (should be ~120 chars for P-256)
|
||||
if (chatPublicKey.length < 100 || chatPublicKey.length > 200) {
|
||||
console.error('[Chat Keys API] Invalid public key length:', chatPublicKey.length);
|
||||
return NextResponse.json({
|
||||
error: `Invalid public key format: expected ~120 characters, got ${chatPublicKey.length}`
|
||||
}, { status: 400 });
|
||||
}
|
||||
|
||||
// Additional validation: try to decode as base64
|
||||
try {
|
||||
const decoded = Buffer.from(chatPublicKey, 'base64');
|
||||
if (decoded.length < 80 || decoded.length > 100) {
|
||||
console.error('[Chat Keys API] Invalid decoded key size:', decoded.length);
|
||||
return NextResponse.json({
|
||||
error: `Invalid public key: decoded size ${decoded.length} bytes (expected ~91 bytes for P-256)`
|
||||
}, { status: 400 });
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[Chat Keys API] Failed to decode public key as base64:', e);
|
||||
return NextResponse.json({ error: 'Public key is not valid base64' }, { status: 400 });
|
||||
}
|
||||
|
||||
// chatPrivateKeyEncrypted should be a JSON string with encrypted data
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db, chatConversations, chatMessages } from '@/db';
|
||||
import { eq, and, isNull, inArray } from 'drizzle-orm';
|
||||
import { getSession } from '@/lib/auth';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
// Get user's conversations
|
||||
const conversations = await db.query.chatConversations.findMany({
|
||||
where: eq(chatConversations.participant1Id, session.user.id),
|
||||
});
|
||||
|
||||
if (conversations.length === 0) {
|
||||
return NextResponse.json({ unreadCount: 0 });
|
||||
}
|
||||
|
||||
// Count unread messages across all conversations
|
||||
const conversationIds = conversations.map(c => c.id);
|
||||
|
||||
const unreadMessages = await db.query.chatMessages.findMany({
|
||||
where: and(
|
||||
inArray(chatMessages.conversationId, conversationIds),
|
||||
isNull(chatMessages.readAt)
|
||||
),
|
||||
});
|
||||
|
||||
// Filter out messages sent by the current user
|
||||
const unreadCount = unreadMessages.filter(
|
||||
msg => msg.senderHandle !== session.user.handle
|
||||
).length;
|
||||
|
||||
return NextResponse.json({ unreadCount });
|
||||
} catch (error) {
|
||||
console.error('Get unread chat count error:', error);
|
||||
return NextResponse.json({ error: 'Failed to get unread count' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db, users } from '@/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const allUsers = await db.select({
|
||||
id: users.id,
|
||||
handle: users.handle,
|
||||
chatPublicKey: users.chatPublicKey,
|
||||
chatPrivateKeyEncrypted: users.chatPrivateKeyEncrypted,
|
||||
}).from(users);
|
||||
|
||||
const results = allUsers.map(user => {
|
||||
let publicKeyInfo = null;
|
||||
if (user.chatPublicKey) {
|
||||
try {
|
||||
const decoded = Buffer.from(user.chatPublicKey, 'base64');
|
||||
publicKeyInfo = {
|
||||
stringLength: user.chatPublicKey.length,
|
||||
decodedBytes: decoded.byteLength,
|
||||
isValidSize: decoded.byteLength === 91,
|
||||
isCorrupted: decoded.byteLength !== 91,
|
||||
};
|
||||
} catch (e) {
|
||||
publicKeyInfo = {
|
||||
error: 'Not valid base64',
|
||||
stringLength: user.chatPublicKey.length,
|
||||
isCorrupted: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
handle: user.handle,
|
||||
hasPublicKey: !!user.chatPublicKey,
|
||||
publicKeyInfo,
|
||||
encryptedPrivateKeyLength: user.chatPrivateKeyEncrypted?.length || 0,
|
||||
};
|
||||
});
|
||||
|
||||
const corrupted = results.filter(r => r.publicKeyInfo?.isCorrupted);
|
||||
|
||||
return NextResponse.json({
|
||||
total: results.length,
|
||||
withKeys: results.filter(r => r.hasPublicKey).length,
|
||||
corrupted: corrupted.length,
|
||||
corruptedUsers: corrupted.map(r => r.handle),
|
||||
allUsers: results,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Debug error:', error);
|
||||
return NextResponse.json({ error: 'Failed to debug keys' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db, users } from '@/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const user = await db.query.users.findFirst({
|
||||
where: (users, { eq }) => eq(users.id, session.user.id),
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
let publicKeyInfo = null;
|
||||
if (user.chatPublicKey) {
|
||||
try {
|
||||
const decoded = Buffer.from(user.chatPublicKey, 'base64');
|
||||
publicKeyInfo = {
|
||||
stringLength: user.chatPublicKey.length,
|
||||
decodedBytes: decoded.byteLength,
|
||||
isValidSize: decoded.byteLength === 91,
|
||||
firstChars: user.chatPublicKey.substring(0, 20),
|
||||
};
|
||||
} catch (e) {
|
||||
publicKeyInfo = {
|
||||
error: 'Not valid base64',
|
||||
stringLength: user.chatPublicKey.length,
|
||||
firstChars: user.chatPublicKey.substring(0, 20),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
handle: user.handle,
|
||||
hasPublicKey: !!user.chatPublicKey,
|
||||
hasEncryptedPrivateKey: !!user.chatPrivateKeyEncrypted,
|
||||
publicKeyInfo,
|
||||
encryptedPrivateKeyLength: user.chatPrivateKeyEncrypted?.length || 0,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Debug error:', error);
|
||||
return NextResponse.json({ error: 'Failed to debug keys' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db, chatMessages } from '@/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const messages = await db.select({
|
||||
id: chatMessages.id,
|
||||
senderHandle: chatMessages.senderHandle,
|
||||
senderChatPublicKey: chatMessages.senderChatPublicKey,
|
||||
createdAt: chatMessages.createdAt,
|
||||
}).from(chatMessages).limit(50);
|
||||
|
||||
const results = messages.map(msg => {
|
||||
let keyInfo = null;
|
||||
if (msg.senderChatPublicKey) {
|
||||
try {
|
||||
const decoded = Buffer.from(msg.senderChatPublicKey, 'base64');
|
||||
keyInfo = {
|
||||
stringLength: msg.senderChatPublicKey.length,
|
||||
decodedBytes: decoded.byteLength,
|
||||
isValidSize: decoded.byteLength === 91,
|
||||
isCorrupted: decoded.byteLength !== 91,
|
||||
firstChars: msg.senderChatPublicKey.substring(0, 20),
|
||||
};
|
||||
} catch (e) {
|
||||
keyInfo = {
|
||||
error: 'Not valid base64',
|
||||
stringLength: msg.senderChatPublicKey.length,
|
||||
isCorrupted: true,
|
||||
firstChars: msg.senderChatPublicKey.substring(0, 20),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: msg.id,
|
||||
senderHandle: msg.senderHandle,
|
||||
createdAt: msg.createdAt,
|
||||
hasSenderKey: !!msg.senderChatPublicKey,
|
||||
keyInfo,
|
||||
};
|
||||
});
|
||||
|
||||
const corrupted = results.filter(r => r.keyInfo?.isCorrupted);
|
||||
|
||||
return NextResponse.json({
|
||||
total: results.length,
|
||||
withKeys: results.filter(r => r.hasSenderKey).length,
|
||||
corrupted: corrupted.length,
|
||||
corruptedMessages: corrupted,
|
||||
allMessages: results,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Debug error:', error);
|
||||
return NextResponse.json({ error: 'Failed to debug messages' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -67,7 +67,7 @@ export async function GET(request: NextRequest) {
|
||||
handle: cachedUser.handle,
|
||||
displayName: cachedUser.displayName || cachedUser.handle,
|
||||
avatarUrl: cachedUser.avatarUrl,
|
||||
chatPublicKey: cachedUser.publicKey, // This is the chat public key
|
||||
chatPublicKey: cachedUser.chatPublicKey, // ECDH key for E2E chat
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -197,7 +197,7 @@ export async function POST(request: NextRequest) {
|
||||
participant1Id: sender.id,
|
||||
participant2Handle: recipientHandle,
|
||||
lastMessageAt: new Date(),
|
||||
lastMessagePreview: '🔒 Encrypted message',
|
||||
lastMessagePreview: 'New message',
|
||||
}).returning();
|
||||
conversation = newConversation;
|
||||
}
|
||||
@@ -227,11 +227,68 @@ export async function POST(request: NextRequest) {
|
||||
await db.update(chatConversations)
|
||||
.set({
|
||||
lastMessageAt: new Date(),
|
||||
lastMessagePreview: '🔒 Encrypted message',
|
||||
lastMessagePreview: 'New message',
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(chatConversations.id, conversation.id));
|
||||
|
||||
// For LOCAL recipients, create/update their conversation too
|
||||
if (!isRemote && recipientUser) {
|
||||
try {
|
||||
console.log('[Chat Send] Creating reciprocal conversation for local recipient:', recipientUser.handle);
|
||||
|
||||
// Check if recipient has a conversation with sender
|
||||
let recipientConversation = await db.query.chatConversations.findFirst({
|
||||
where: and(
|
||||
eq(chatConversations.participant1Id, recipientUser.id),
|
||||
eq(chatConversations.participant2Handle, sender.handle)
|
||||
),
|
||||
});
|
||||
|
||||
if (!recipientConversation) {
|
||||
// Create conversation for recipient
|
||||
const [newRecipientConv] = await db.insert(chatConversations).values({
|
||||
participant1Id: recipientUser.id,
|
||||
participant2Handle: sender.handle,
|
||||
lastMessageAt: new Date(),
|
||||
lastMessagePreview: 'New message',
|
||||
}).returning();
|
||||
recipientConversation = newRecipientConv;
|
||||
console.log('[Chat Send] Created new conversation for recipient');
|
||||
} else {
|
||||
// Update existing conversation
|
||||
await db.update(chatConversations)
|
||||
.set({
|
||||
lastMessageAt: new Date(),
|
||||
lastMessagePreview: 'New message',
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(chatConversations.id, recipientConversation.id));
|
||||
console.log('[Chat Send] Updated existing conversation for recipient');
|
||||
}
|
||||
|
||||
// Insert message into recipient's conversation
|
||||
await db.insert(chatMessages).values({
|
||||
conversationId: recipientConversation.id,
|
||||
senderHandle: sender.handle,
|
||||
senderDisplayName: sender.displayName,
|
||||
senderAvatarUrl: sender.avatarUrl,
|
||||
senderNodeDomain: null,
|
||||
encryptedContent,
|
||||
senderEncryptedContent,
|
||||
senderChatPublicKey: data.senderPublicKey || sender.chatPublicKey,
|
||||
swarmMessageId: `${swarmMessageId}-recipient`, // Make it unique for recipient's copy
|
||||
deliveredAt: new Date(),
|
||||
readAt: null,
|
||||
});
|
||||
|
||||
console.log('[Chat Send] Reciprocal message created for local recipient');
|
||||
} catch (recipError) {
|
||||
console.error('[Chat Send] Failed to create reciprocal conversation:', recipError);
|
||||
// Don't fail the whole request - sender's message was still saved
|
||||
}
|
||||
}
|
||||
|
||||
// If remote, send to their node
|
||||
if (isRemote && recipientNodeDomain) {
|
||||
// ... (remote logic remains similar but add logs)
|
||||
|
||||
Reference in New Issue
Block a user