feat: Implement a new chat widget with enhanced encryption handling and supporting utility scripts, replacing the old chat page.
This commit is contained in:
@@ -1,576 +0,0 @@
|
||||
/* Chat Page Styles */
|
||||
|
||||
.chat-page {
|
||||
height: 100vh;
|
||||
/* Use dynamic viewport height for mobile browsers */
|
||||
height: 100dvh;
|
||||
max-height: 100dvh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.chat-container {
|
||||
display: grid;
|
||||
grid-template-columns: 400px 1fr;
|
||||
height: 100%;
|
||||
border-left: 1px solid var(--border);
|
||||
border-right: 1px solid var(--border);
|
||||
overflow: hidden;
|
||||
background: var(--background);
|
||||
}
|
||||
|
||||
/* Sidebar */
|
||||
.chat-sidebar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-right: 1px solid var(--border);
|
||||
background: var(--background);
|
||||
}
|
||||
|
||||
.chat-sidebar-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 20px 24px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.chat-sidebar-header h1 {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.chat-search {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 16px 24px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--background-secondary);
|
||||
}
|
||||
|
||||
.chat-search svg {
|
||||
color: var(--foreground-tertiary);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.chat-search input {
|
||||
flex: 1;
|
||||
background: transparent;
|
||||
border: none;
|
||||
outline: none;
|
||||
color: var(--foreground);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.chat-search input::placeholder {
|
||||
color: var(--foreground-tertiary);
|
||||
}
|
||||
|
||||
/* Conversations List */
|
||||
.conversations-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.conversation-item {
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
padding: 16px 24px;
|
||||
border: none;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: transparent;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s ease;
|
||||
}
|
||||
|
||||
.conversation-item:hover {
|
||||
background: var(--background-secondary);
|
||||
}
|
||||
|
||||
.conversation-item.active {
|
||||
background: var(--background-tertiary);
|
||||
border-left: 3px solid var(--accent);
|
||||
}
|
||||
|
||||
.conversation-avatar {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: var(--radius-full);
|
||||
background: var(--background-tertiary);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.conversation-avatar img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.conversation-avatar span {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.conversation-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.conversation-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.conversation-name {
|
||||
font-weight: 600;
|
||||
font-size: 15px;
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.unread-badge {
|
||||
background: var(--accent);
|
||||
color: var(--background);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
padding: 2px 8px;
|
||||
border-radius: var(--radius-full);
|
||||
min-width: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.conversation-handle {
|
||||
font-size: 13px;
|
||||
color: var(--foreground-secondary);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.conversation-preview {
|
||||
font-size: 14px;
|
||||
color: var(--foreground-tertiary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* Main Chat Area */
|
||||
.chat-main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--background);
|
||||
}
|
||||
|
||||
.chat-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
padding: 20px 24px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--background-secondary);
|
||||
}
|
||||
|
||||
.back-button {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.chat-header-avatar {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: var(--radius-full);
|
||||
background: var(--background-tertiary);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.chat-header-avatar img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.chat-header-avatar span {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.chat-header-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.chat-header-info h2 {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
margin: 0 0 2px 0;
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.chat-header-info p {
|
||||
font-size: 13px;
|
||||
color: var(--foreground-secondary);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* Messages */
|
||||
.chat-messages {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.message {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
max-width: 70%;
|
||||
}
|
||||
|
||||
.message.sent {
|
||||
flex-direction: row-reverse;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.message-avatar {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: var(--radius-full);
|
||||
background: var(--background-tertiary);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.message-avatar img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.message-avatar span {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.message-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.message.sent .message-content {
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
.message-bubble {
|
||||
padding: 12px 16px;
|
||||
border-radius: var(--radius-lg);
|
||||
background: var(--background-secondary);
|
||||
border: 1px solid var(--border);
|
||||
word-wrap: break-word;
|
||||
}
|
||||
|
||||
.message.sent .message-bubble {
|
||||
background: var(--accent);
|
||||
color: var(--background);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.encrypted-indicator {
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
opacity: 0.7;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.encrypted-preview {
|
||||
font-size: 13px;
|
||||
font-family: 'Courier New', monospace;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.message-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 11px;
|
||||
color: var(--foreground-tertiary);
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.delivery-status {
|
||||
color: var(--foreground-secondary);
|
||||
}
|
||||
|
||||
/* Chat Input */
|
||||
.chat-input {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
padding: 20px 24px;
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--background-secondary);
|
||||
}
|
||||
|
||||
.chat-input input {
|
||||
flex: 1;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-size: 14px;
|
||||
outline: none;
|
||||
transition: border-color 0.15s ease;
|
||||
}
|
||||
|
||||
.chat-input input:focus {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.chat-input input::placeholder {
|
||||
color: var(--foreground-tertiary);
|
||||
}
|
||||
|
||||
.send-button {
|
||||
background: var(--accent);
|
||||
color: var(--background);
|
||||
border: none;
|
||||
}
|
||||
|
||||
.send-button:hover:not(:disabled) {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
|
||||
.send-button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* Empty States */
|
||||
.chat-empty-state {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 16px;
|
||||
padding: 48px 24px;
|
||||
text-align: center;
|
||||
color: var(--foreground-tertiary);
|
||||
}
|
||||
|
||||
.chat-empty-state svg {
|
||||
opacity: 0.3;
|
||||
}
|
||||
|
||||
.chat-empty-state h2,
|
||||
.chat-empty-state h3 {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: var(--foreground-secondary);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.chat-empty-state p {
|
||||
font-size: 14px;
|
||||
color: var(--foreground-tertiary);
|
||||
margin: 0;
|
||||
max-width: 320px;
|
||||
}
|
||||
|
||||
.chat-loading {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 16px;
|
||||
padding: 48px 24px;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border: 3px solid var(--border);
|
||||
border-top-color: var(--accent);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* Modal */
|
||||
.modal-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
background: var(--background-secondary);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
padding: 32px;
|
||||
max-width: 480px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.modal-content h2 {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
margin: 0 0 8px 0;
|
||||
}
|
||||
|
||||
.modal-content p {
|
||||
font-size: 14px;
|
||||
color: var(--foreground-secondary);
|
||||
margin: 0 0 24px 0;
|
||||
}
|
||||
|
||||
.modal-content form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.modal-content input {
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-size: 14px;
|
||||
outline: none;
|
||||
transition: border-color 0.15s ease;
|
||||
}
|
||||
|
||||
.modal-content input:focus {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.modal-actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
/* Buttons */
|
||||
.btn-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: var(--radius-md);
|
||||
border: 1px solid var(--border);
|
||||
background: transparent;
|
||||
color: var(--foreground);
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
|
||||
.btn-icon:hover:not(:disabled) {
|
||||
background: var(--background-tertiary);
|
||||
border-color: var(--border-hover);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 10px 20px;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
border-radius: var(--radius-md);
|
||||
border: none;
|
||||
background: var(--accent);
|
||||
color: var(--background);
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
|
||||
.btn-primary:hover:not(:disabled) {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
|
||||
.btn-primary:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 10px 20px;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
border-radius: var(--radius-md);
|
||||
border: 1px solid var(--border);
|
||||
background: transparent;
|
||||
color: var(--foreground);
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: var(--background-tertiary);
|
||||
border-color: var(--border-hover);
|
||||
}
|
||||
|
||||
/* Mobile Responsive */
|
||||
@media (max-width: 768px) {
|
||||
.chat-container {
|
||||
grid-template-columns: 1fr;
|
||||
border-radius: 0;
|
||||
border-left: none;
|
||||
border-right: none;
|
||||
}
|
||||
|
||||
.mobile-hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.back-button {
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
.chat-sidebar {
|
||||
border-right: none;
|
||||
}
|
||||
|
||||
.message {
|
||||
max-width: 85%;
|
||||
}
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useAuth } from '@/lib/contexts/AuthContext';
|
||||
import { useChatEncryption } from '@/lib/hooks/useChatEncryption';
|
||||
import { MessageCircle, Send, ArrowLeft, Search, Plus, Lock, Shield, Key } from 'lucide-react';
|
||||
import { formatFullHandle } from '@/lib/utils/handle';
|
||||
import './chat.css';
|
||||
|
||||
interface Conversation {
|
||||
id: string;
|
||||
participant2: {
|
||||
handle: string;
|
||||
displayName: string;
|
||||
avatarUrl: string | null;
|
||||
chatPublicKey: string | null;
|
||||
};
|
||||
lastMessageAt: string;
|
||||
lastMessagePreview: string;
|
||||
unreadCount: number;
|
||||
}
|
||||
|
||||
interface Message {
|
||||
id: string;
|
||||
senderHandle: string;
|
||||
senderDisplayName?: string;
|
||||
senderAvatarUrl?: string;
|
||||
senderPublicKey?: string;
|
||||
encryptedContent: string;
|
||||
decryptedContent?: string;
|
||||
isSentByMe: boolean;
|
||||
deliveredAt?: string;
|
||||
readAt?: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export default function ChatPage() {
|
||||
const { user } = useAuth();
|
||||
const { keys, isReady, hasKeys, isRegistering, needsPasswordToRestore, generateAndRegisterKeys, restoreKeysWithPassword, encryptMessage, decryptMessage } = useChatEncryption();
|
||||
const [conversations, setConversations] = useState<Conversation[]>([]);
|
||||
const [selectedConversation, setSelectedConversation] = useState<Conversation | null>(null);
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [newMessage, setNewMessage] = useState('');
|
||||
const [newChatHandle, setNewChatHandle] = useState('');
|
||||
const [showNewChat, setShowNewChat] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [sending, setSending] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [recipientPublicKey, setRecipientPublicKey] = useState<string | null>(null);
|
||||
const [showPasswordModal, setShowPasswordModal] = useState(false);
|
||||
const [password, setPassword] = useState('');
|
||||
const [passwordError, setPasswordError] = useState('');
|
||||
const [isProcessingPassword, setIsProcessingPassword] = useState(false);
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => { if (user && hasKeys) loadConversations(); }, [user, hasKeys]);
|
||||
useEffect(() => { if (selectedConversation && hasKeys) { loadMessages(selectedConversation.id); markAsRead(selectedConversation.id); fetchRecipientKey(selectedConversation.participant2.handle); } }, [selectedConversation, hasKeys]);
|
||||
useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages]);
|
||||
|
||||
const fetchRecipientKey = async (handle: string) => { try { const res = await fetch(`/api/users/${encodeURIComponent(handle)}`); const data = await res.json(); setRecipientPublicKey(data.user?.chatPublicKey || null); } catch { setRecipientPublicKey(null); } };
|
||||
const loadConversations = async () => { try { const res = await fetch('/api/swarm/chat/conversations'); const data = await res.json(); setConversations(data.conversations || []); } catch { } finally { setLoading(false); } };
|
||||
const loadMessages = async (conversationId: string) => {
|
||||
console.log('[LoadMessages] Starting load for conversation:', conversationId);
|
||||
try {
|
||||
// Ensure we have the recipient's key before trying to decrypt
|
||||
let chatPartnerKey = selectedConversation?.participant2?.chatPublicKey || recipientPublicKey;
|
||||
|
||||
console.log('[LoadMessages] Initial chatPartnerKey:', !!chatPartnerKey);
|
||||
|
||||
// If we don't have the key yet, fetch it
|
||||
if (!chatPartnerKey && selectedConversation?.participant2?.handle) {
|
||||
console.log('[LoadMessages] Fetching recipient key for:', selectedConversation.participant2.handle);
|
||||
try {
|
||||
const userRes = await fetch(`/api/users/${encodeURIComponent(selectedConversation.participant2.handle)}`);
|
||||
const userData = await userRes.json();
|
||||
chatPartnerKey = userData.user?.chatPublicKey || null;
|
||||
console.log('[LoadMessages] Fetched chatPartnerKey:', !!chatPartnerKey);
|
||||
if (chatPartnerKey) setRecipientPublicKey(chatPartnerKey);
|
||||
} catch (e) {
|
||||
console.error('[LoadMessages] Failed to fetch recipient key:', e);
|
||||
}
|
||||
}
|
||||
|
||||
const res = await fetch(`/api/swarm/chat/messages?conversationId=${conversationId}`);
|
||||
const data = await res.json();
|
||||
|
||||
console.log('[LoadMessages] Received messages:', data.messages?.length || 0);
|
||||
|
||||
const decrypted = await Promise.all((data.messages || []).map(async (msg: Message & { isE2E?: boolean }, idx: number) => {
|
||||
console.log(`[LoadMessages] Processing message ${idx}:`, {
|
||||
id: msg.id,
|
||||
isSentByMe: msg.isSentByMe,
|
||||
hasSenderPublicKey: !!msg.senderPublicKey,
|
||||
isE2EFlag: msg.isE2E
|
||||
});
|
||||
|
||||
try {
|
||||
// Check if this is an E2E encrypted message (has senderPublicKey)
|
||||
// or a legacy RSA message (no senderPublicKey)
|
||||
const isE2E = !!msg.senderPublicKey;
|
||||
|
||||
if (!isE2E) {
|
||||
console.log(`[LoadMessages] Message ${idx} is legacy RSA`);
|
||||
// Legacy RSA message - can't decrypt client-side
|
||||
return { ...msg, decryptedContent: '[Legacy encrypted message]' };
|
||||
}
|
||||
|
||||
// ECDH: Both parties derive same shared secret
|
||||
// For messages I sent: use recipient's public key (chatPartnerKey)
|
||||
// For messages I received: use sender's public key
|
||||
const otherPartyKey = msg.isSentByMe ? chatPartnerKey : msg.senderPublicKey;
|
||||
|
||||
console.log(`[LoadMessages] Message ${idx} otherPartyKey:`, !!otherPartyKey, 'isSentByMe:', msg.isSentByMe);
|
||||
|
||||
if (!otherPartyKey) {
|
||||
console.warn('Missing key for decryption. isSentByMe:', msg.isSentByMe, 'chatPartnerKey:', !!chatPartnerKey);
|
||||
return { ...msg, decryptedContent: '[Missing decryption key]' };
|
||||
}
|
||||
|
||||
if (msg.encryptedContent) {
|
||||
console.log(`[LoadMessages] Calling decryptMessage for message ${idx}`);
|
||||
const decrypted = await decryptMessage(msg.encryptedContent, otherPartyKey);
|
||||
console.log(`[LoadMessages] Message ${idx} decrypted successfully`);
|
||||
return { ...msg, decryptedContent: decrypted };
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[LoadMessages] Decrypt error for message ${idx}:`, err, 'msg:', msg.id, 'isSentByMe:', msg.isSentByMe);
|
||||
}
|
||||
return { ...msg, decryptedContent: '[Unable to decrypt]' };
|
||||
}));
|
||||
|
||||
console.log('[LoadMessages] Setting messages:', decrypted.length);
|
||||
setMessages(decrypted);
|
||||
} catch (err) {
|
||||
console.error('[LoadMessages] Load messages error:', err);
|
||||
}
|
||||
};
|
||||
const markAsRead = async (conversationId: string) => { try { await fetch('/api/swarm/chat/messages', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ conversationId }) }); setConversations(prev => prev.map(c => c.id === conversationId ? { ...c, unreadCount: 0 } : c)); } catch { } };
|
||||
const sendMessage = async (e: React.FormEvent) => { e.preventDefault(); if (!newMessage.trim() || !selectedConversation || !recipientPublicKey) return; setSending(true); try { const encrypted = await encryptMessage(newMessage, recipientPublicKey); const res = await fetch('/api/swarm/chat/send', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ recipientHandle: selectedConversation.participant2.handle, encryptedContent: encrypted, senderPublicKey: keys?.publicKey }) }); if (res.ok) { setMessages(prev => [...prev, { id: crypto.randomUUID(), senderHandle: user?.handle || '', encryptedContent: encrypted, decryptedContent: newMessage, isSentByMe: true, createdAt: new Date().toISOString() }]); setNewMessage(''); loadConversations(); } } catch { } finally { setSending(false); } };
|
||||
const startNewChat = async (e: React.FormEvent) => { e.preventDefault(); if (!newChatHandle.trim()) return; setSending(true); try { const cleanHandle = newChatHandle.replace(/^@/, ''); const res = await fetch(`/api/users/${encodeURIComponent(cleanHandle)}`); const data = await res.json(); if (!data.user?.chatPublicKey) { alert('This user has not enabled encrypted chat yet.'); return; } const encrypted = await encryptMessage('Hey! 👋', data.user.chatPublicKey); const sendRes = await fetch('/api/swarm/chat/send', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ recipientHandle: cleanHandle, encryptedContent: encrypted, senderPublicKey: keys?.publicKey }) }); if (sendRes.ok) { setShowNewChat(false); setNewChatHandle(''); loadConversations(); } } catch { } finally { setSending(false); } };
|
||||
const handlePasswordSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!password) return; setPasswordError(''); setIsProcessingPassword(true); try { if (needsPasswordToRestore) { const success = await restoreKeysWithPassword(password); if (!success) { setPasswordError('Incorrect password.'); return; } } else { await generateAndRegisterKeys(password); } setShowPasswordModal(false); setPassword(''); } catch { setPasswordError('Failed. Please try again.'); } finally { setIsProcessingPassword(false); } };
|
||||
const filteredConversations = conversations.filter(conv => conv.participant2.displayName?.toLowerCase().includes(searchQuery.toLowerCase()) || conv.participant2.handle.toLowerCase().includes(searchQuery.toLowerCase()));
|
||||
|
||||
if (!user) return <div className="chat-page"><div className="chat-empty-state"><MessageCircle size={64} /><h2>Sign in to use Swarm Chat</h2><p>End-to-end encrypted messaging</p></div></div>;
|
||||
if (!isReady) return <div className="chat-page"><div className="chat-empty-state"><div className="spinner" /><p>Loading encryption...</p></div></div>;
|
||||
if (!hasKeys) return (
|
||||
<div className="chat-page">
|
||||
<div className="chat-empty-state">
|
||||
<Shield size={64} />
|
||||
<h2>{needsPasswordToRestore ? 'Restore Your Chat Keys' : 'Enable End-to-End Encryption'}</h2>
|
||||
<p>{needsPasswordToRestore ? 'Enter your password to restore your encrypted chat keys.' : 'Generate encryption keys to start secure messaging.'}</p>
|
||||
<p className="text-sm text-gray-500 mt-2"><Lock size={14} className="inline mr-1" />Your private key is encrypted with your password.</p>
|
||||
<button className="btn-primary mt-4" onClick={() => setShowPasswordModal(true)} disabled={isRegistering}><Key size={18} className="mr-2" />{needsPasswordToRestore ? 'Restore Keys' : 'Enable Encrypted Chat'}</button>
|
||||
</div>
|
||||
{showPasswordModal && (
|
||||
<div className="modal-overlay" onClick={() => setShowPasswordModal(false)}>
|
||||
<div className="modal-content" onClick={(e) => e.stopPropagation()}>
|
||||
<h2>{needsPasswordToRestore ? 'Enter Your Password' : 'Secure Your Chat Keys'}</h2>
|
||||
<p>{needsPasswordToRestore ? 'Enter your account password to decrypt your chat keys.' : 'Enter your account password to encrypt your chat keys.'}</p>
|
||||
<form onSubmit={handlePasswordSubmit}>
|
||||
<input type="password" placeholder="Your account password" value={password} onChange={(e) => setPassword(e.target.value)} autoFocus />
|
||||
{passwordError && <p className="text-red-500 text-sm mt-2">{passwordError}</p>}
|
||||
<div className="modal-actions">
|
||||
<button type="button" className="btn-secondary" onClick={() => { setShowPasswordModal(false); setPassword(''); setPasswordError(''); }}>Cancel</button>
|
||||
<button type="submit" className="btn-primary" disabled={isProcessingPassword || !password}>{isProcessingPassword ? 'Processing...' : (needsPasswordToRestore ? 'Restore' : 'Enable')}</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="chat-page">
|
||||
<div className="chat-container">
|
||||
<div className={`chat-sidebar ${selectedConversation ? 'mobile-hidden' : ''}`}>
|
||||
<div className="chat-sidebar-header"><h1><Lock size={18} className="inline mr-2" />Messages</h1><button className="btn-icon" onClick={() => setShowNewChat(true)} title="New chat"><Plus size={20} /></button></div>
|
||||
<div className="chat-search"><Search size={18} /><input type="text" placeholder="Search conversations..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} /></div>
|
||||
{loading ? <div className="chat-loading"><div className="spinner" /><p>Loading...</p></div> : filteredConversations.length === 0 ? <div className="chat-empty-state"><MessageCircle size={48} /><h3>No conversations</h3><button className="btn-primary" onClick={() => setShowNewChat(true)}><Plus size={18} />New Chat</button></div> : <div className="conversations-list">{filteredConversations.map((conv) => <button key={conv.id} className={`conversation-item ${selectedConversation?.id === conv.id ? 'active' : ''}`} onClick={() => setSelectedConversation(conv)}><div className="conversation-avatar">{conv.participant2.avatarUrl ? <img src={conv.participant2.avatarUrl} alt="" /> : <span>{(conv.participant2.displayName || conv.participant2.handle).charAt(0).toUpperCase()}</span>}</div><div className="conversation-content"><div className="conversation-header"><span className="conversation-name">{conv.participant2.displayName}</span>{conv.unreadCount > 0 && <span className="unread-badge">{conv.unreadCount}</span>}</div><div className="conversation-handle">{formatFullHandle(conv.participant2.handle)}</div><div className="conversation-preview"><Lock size={12} className="inline mr-1" />{conv.lastMessagePreview}</div></div></button>)}</div>}
|
||||
</div>
|
||||
<div className={`chat-main ${!selectedConversation ? 'mobile-hidden' : ''}`}>
|
||||
{selectedConversation ? <>
|
||||
<div className="chat-header"><button className="btn-icon back-button" onClick={() => setSelectedConversation(null)}><ArrowLeft size={20} /></button><div className="chat-header-avatar">{selectedConversation.participant2.avatarUrl ? <img src={selectedConversation.participant2.avatarUrl} alt="" /> : <span>{(selectedConversation.participant2.displayName || selectedConversation.participant2.handle).charAt(0).toUpperCase()}</span>}</div><div className="chat-header-info"><h2>{selectedConversation.participant2.displayName}</h2><p><Lock size={12} className="inline mr-1" />{formatFullHandle(selectedConversation.participant2.handle)}</p></div></div>
|
||||
<div className="chat-messages"><div className="encryption-notice"><Shield size={16} /><span>Messages are end-to-end encrypted.</span></div>{messages.map((msg) => <div key={msg.id} className={`message ${msg.isSentByMe ? 'sent' : 'received'}`}>{!msg.isSentByMe && <div className="message-avatar">{msg.senderAvatarUrl ? <img src={msg.senderAvatarUrl} alt="" /> : <span>{(msg.senderDisplayName || msg.senderHandle).charAt(0).toUpperCase()}</span>}</div>}<div className="message-content"><div className="message-bubble">{msg.decryptedContent || msg.encryptedContent}</div><div className="message-meta"><span>{new Date(msg.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span>{msg.isSentByMe && <span className="delivery-status">{msg.readAt ? '✓✓' : msg.deliveredAt ? '✓' : '○'}</span>}</div></div></div>)}<div ref={messagesEndRef} /></div>
|
||||
<form className="chat-input" onSubmit={sendMessage}><input type="text" placeholder={recipientPublicKey ? "Type a message..." : "Recipient hasn't enabled encryption..."} value={newMessage} onChange={(e) => setNewMessage(e.target.value)} disabled={sending || !recipientPublicKey} /><button type="submit" className="btn-icon send-button" disabled={sending || !newMessage.trim() || !recipientPublicKey}><Send size={20} /></button></form>
|
||||
</> : <div className="chat-empty-state"><MessageCircle size={64} /><h2>Select a conversation</h2></div>}
|
||||
</div>
|
||||
</div>
|
||||
{showNewChat && <div className="modal-overlay" onClick={() => setShowNewChat(false)}><div className="modal-content" onClick={(e) => e.stopPropagation()}><h2>Start New Chat</h2><form onSubmit={startNewChat}><input type="text" placeholder="user@node.domain" value={newChatHandle} onChange={(e) => setNewChatHandle(e.target.value)} autoFocus /><div className="modal-actions"><button type="button" className="btn-secondary" onClick={() => setShowNewChat(false)}>Cancel</button><button type="submit" className="btn-primary" disabled={sending || !newChatHandle.trim()}>Start Chat</button></div></form></div></div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user