Dateien nach "frontend/src/tools" hochladen

This commit is contained in:
2026-05-27 19:00:39 +02:00
parent a2799155e6
commit 2da50e2c71

View File

@@ -0,0 +1,360 @@
import { useState, useEffect, useRef } from 'react';
import { api, S } from '../lib.js';
import { UserIcon, TrashIcon } from '../icons.jsx';
// ── E2E Crypto ────────────────────────────────────────────────────────────────
const LS_KEY = 'dd_msg_keypair';
async function getOrCreateKeyPair() {
const stored = localStorage.getItem(LS_KEY);
if (stored) {
try {
const { pub, priv } = JSON.parse(stored);
const publicKey = await crypto.subtle.importKey('jwk', pub, { name:'ECDH', namedCurve:'P-256' }, true, []);
const privateKey = await crypto.subtle.importKey('jwk', priv, { name:'ECDH', namedCurve:'P-256' }, true, ['deriveKey']);
return { publicKey, privateKey, pubJwk: pub };
} catch { localStorage.removeItem(LS_KEY); }
}
const kp = await crypto.subtle.generateKey({ name:'ECDH', namedCurve:'P-256' }, true, ['deriveKey']);
const pub = await crypto.subtle.exportKey('jwk', kp.publicKey);
const priv = await crypto.subtle.exportKey('jwk', kp.privateKey);
localStorage.setItem(LS_KEY, JSON.stringify({ pub, priv }));
return { publicKey: kp.publicKey, privateKey: kp.privateKey, pubJwk: pub };
}
async function deriveSharedKey(myPrivate, theirPublicJwk) {
const theirKey = await crypto.subtle.importKey(
'jwk', theirPublicJwk, { name:'ECDH', namedCurve:'P-256' }, false, []
);
return crypto.subtle.deriveKey(
{ name:'ECDH', public: theirKey },
myPrivate,
{ name:'AES-GCM', length:256 },
false, ['encrypt','decrypt']
);
}
async function encryptMsg(sharedKey, text) {
const iv = crypto.getRandomValues(new Uint8Array(12));
const enc = await crypto.subtle.encrypt({ name:'AES-GCM', iv }, sharedKey, new TextEncoder().encode(text));
return {
encrypted_content: btoa(String.fromCharCode(...new Uint8Array(enc))),
iv: btoa(String.fromCharCode(...iv)),
};
}
async function decryptMsg(sharedKey, encrypted_content, ivB64) {
const enc = Uint8Array.from(atob(encrypted_content), c => c.charCodeAt(0));
const ivArr = Uint8Array.from(atob(ivB64), c => c.charCodeAt(0));
const dec = await crypto.subtle.decrypt({ name:'AES-GCM', iv: ivArr }, sharedKey, enc);
return new TextDecoder().decode(dec);
}
// ── Main Component ────────────────────────────────────────────────────────────
export default function Nachrichten({ toast, mobile }) {
const [kp, setKp] = useState(null);
const [users, setUsers] = useState([]);
const [activeUser, setActiveUser] = useState(null);
const [messages, setMessages] = useState([]);
const [sharedKey, setSharedKey] = useState(null);
const [decrypted, setDecrypted] = useState({});
const [text, setText] = useState('');
const [sending, setSending] = useState(false);
const bottomRef = useRef(null);
const pollRef = useRef(null);
// Init key pair + register public key
useEffect(() => {
getOrCreateKeyPair().then(async k => {
setKp(k);
try { await api('/tools/nachrichten/keys', { body: { public_key: JSON.stringify(k.pubJwk) } }); }
catch {}
});
loadUsers();
}, []);
const loadUsers = async () => {
try { setUsers(await api('/tools/nachrichten/users')); } catch {}
};
// Poll messages in active conversation
useEffect(() => {
clearInterval(pollRef.current);
if (!activeUser) return;
loadMessages(activeUser.id);
pollRef.current = setInterval(() => loadMessages(activeUser.id), 15000);
return () => clearInterval(pollRef.current);
}, [activeUser?.id]);
// Derive shared key when conversation or own key changes
useEffect(() => {
setSharedKey(null);
setDecrypted({});
if (!kp || !activeUser?.public_key) return;
try {
deriveSharedKey(kp.privateKey, JSON.parse(activeUser.public_key))
.then(setSharedKey)
.catch(() => {});
} catch {}
}, [activeUser?.id, kp]);
// Decrypt messages whenever messages or sharedKey changes
useEffect(() => {
if (!sharedKey || !messages.length) { setDecrypted({}); return; }
let cancelled = false;
(async () => {
const result = {};
for (const m of messages) {
if (cancelled) return;
try { result[m.id] = await decryptMsg(sharedKey, m.encrypted_content, m.iv); }
catch { result[m.id] = '🔒 Nicht entschlüsselbar'; }
}
if (!cancelled) setDecrypted(result);
})();
return () => { cancelled = true; };
}, [messages, sharedKey]);
// Scroll to bottom on new messages
useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior:'smooth' });
}, [messages.length]);
const loadMessages = async (userId) => {
try {
const msgs = await api(`/tools/nachrichten/messages/${userId}`);
setMessages(msgs);
await loadUsers();
} catch {}
};
const selectUser = (u) => {
setActiveUser(u);
setMessages([]);
setDecrypted({});
};
const send = async () => {
if (!text.trim() || !kp || !activeUser) return;
if (!activeUser.public_key) { toast('Empfänger hat noch kein Schlüsselpaar', 'error'); return; }
if (!sharedKey) { toast('Schlüssel wird noch vorbereitet…', 'error'); return; }
setSending(true);
try {
const { encrypted_content, iv } = await encryptMsg(sharedKey, text.trim());
await api(`/tools/nachrichten/messages/${activeUser.id}`, { body: { encrypted_content, iv } });
setText('');
await loadMessages(activeUser.id);
} catch (e) { toast(e.message, 'error'); }
setSending(false);
};
const deleteMsg = async (id) => {
try {
await api(`/tools/nachrichten/messages/${id}`, { method:'DELETE' });
setMessages(p => p.filter(m => m.id !== id));
} catch (e) { toast(e.message, 'error'); }
};
const deleteConversation = async () => {
try {
await api(`/tools/nachrichten/conversation/${activeUser.id}`, { method:'DELETE' });
setMessages([]);
await loadUsers();
} catch (e) { toast(e.message, 'error'); }
};
const showList = !mobile || !activeUser;
const showChat = !mobile || !!activeUser;
const containerH = mobile
? 'calc(100dvh - 56px - env(safe-area-inset-bottom, 0px))'
: '100vh';
return (
<div style={{ display:'flex', height:containerH, overflow:'hidden', background:'#111114' }}>
{/* ── Conversation List ────────────────────────────────────────── */}
{showList && (
<div style={{
width: mobile ? '100%' : 240,
borderRight: mobile ? 'none' : '1px solid rgba(255,255,255,0.06)',
display:'flex', flexDirection:'column', background:'#0d0d0f', flexShrink:0,
}}>
<div style={{ padding:'16px 14px 12px', borderBottom:'1px solid rgba(255,255,255,0.06)' }}>
<div style={{ ...S.head, marginBottom:0 }}>NACHRICHTEN</div>
</div>
<div style={{ flex:1, overflowY:'auto' }}>
{users.length === 0 ? (
<div style={{ color:'rgba(255,255,255,0.3)', fontSize:11, fontFamily:'monospace',
padding:18, textAlign:'center', lineHeight:1.6 }}>
Keine anderen Benutzer
</div>
) : users.map(u => (
<button key={u.id} onClick={() => selectUser(u)} style={{
width:'100%', padding:'11px 14px', border:'none', textAlign:'left', cursor:'pointer',
background: activeUser?.id === u.id ? 'rgba(78,205,196,0.07)' : 'transparent',
borderLeft: `2px solid ${activeUser?.id === u.id ? '#4ecdc4' : 'transparent'}`,
display:'flex', alignItems:'center', gap:10, transition:'background 0.1s',
}}>
<div style={{ width:32, height:32, borderRadius:'50%', flexShrink:0,
background:'linear-gradient(135deg,rgba(255,107,157,0.25),rgba(78,205,196,0.25))',
border:'1px solid rgba(255,255,255,0.08)',
display:'flex', alignItems:'center', justifyContent:'center' }}>
<UserIcon size={14} color="rgba(255,255,255,0.55)"/>
</div>
<div style={{ flex:1, minWidth:0 }}>
<div style={{
color: u.unread > 0 ? '#fff' : 'rgba(255,255,255,0.65)',
fontSize:12, fontFamily:'monospace',
fontWeight: u.unread > 0 ? 700 : 400,
whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis',
}}>{u.username}</div>
{u.last_message_at && (
<div style={{ color:'rgba(255,255,255,0.28)', fontSize:9, fontFamily:'monospace', marginTop:2 }}>
{new Date(u.last_message_at).toLocaleDateString('de-DE',
{ day:'numeric', month:'short', hour:'2-digit', minute:'2-digit' })}
</div>
)}
</div>
{u.unread > 0 && (
<div style={{ background:'#4ecdc4', color:'#000', borderRadius:10,
fontSize:9, fontFamily:'monospace', padding:'2px 7px',
fontWeight:700, flexShrink:0 }}>{u.unread}</div>
)}
</button>
))}
</div>
</div>
)}
{/* ── Chat Panel ───────────────────────────────────────────────── */}
{showChat && (
<div style={{ flex:1, display:'flex', flexDirection:'column', overflow:'hidden', minWidth:0 }}>
{!activeUser ? (
<div style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center',
flexDirection:'column', gap:10 }}>
<div style={{ fontSize:40, opacity:0.15 }}></div>
<div style={{ color:'rgba(255,255,255,0.2)', fontFamily:'monospace', fontSize:11 }}>
Benutzer auswählen
</div>
</div>
) : (
<>
{/* Header */}
<div style={{ padding:'10px 14px', borderBottom:'1px solid rgba(255,255,255,0.06)',
display:'flex', alignItems:'center', gap:10, background:'#0d0d0f', flexShrink:0 }}>
{mobile && (
<button onClick={() => setActiveUser(null)} style={{ background:'transparent', border:'none',
cursor:'pointer', color:'#4ecdc4', fontFamily:'monospace', fontSize:20, padding:'0 4px', lineHeight:1 }}>
</button>
)}
<div style={{ width:28, height:28, borderRadius:'50%', flexShrink:0,
background:'linear-gradient(135deg,rgba(255,107,157,0.25),rgba(78,205,196,0.25))',
border:'1px solid rgba(255,255,255,0.08)',
display:'flex', alignItems:'center', justifyContent:'center' }}>
<UserIcon size={12} color="rgba(255,255,255,0.55)"/>
</div>
<div style={{ flex:1 }}>
<div style={{ color:'#fff', fontSize:13, fontFamily:'monospace' }}>{activeUser.username}</div>
<div style={{ color:'rgba(78,205,196,0.55)', fontSize:8, fontFamily:'monospace', letterSpacing:1.5, marginTop:1 }}>
🔒 E2E VERSCHLÜSSELT
</div>
</div>
<button onClick={deleteConversation} style={{ ...S.btn('#ff6b9d', true), fontSize:10 }}>
Verlauf löschen
</button>
</div>
{/* Messages */}
<div style={{ flex:1, overflowY:'auto', padding:'14px', display:'flex', flexDirection:'column', gap:10 }}>
{!activeUser.public_key && (
<div style={{ background:'rgba(255,230,109,0.06)', border:'1px solid rgba(255,230,109,0.2)',
borderRadius:8, padding:'10px 14px', color:'#ffe66d',
fontSize:11, fontFamily:'monospace', textAlign:'center', lineHeight:1.7 }}>
Dieser Benutzer hat das Nachrichten-Tool noch nicht geöffnet und besitzt noch kein Schlüsselpaar.
</div>
)}
{messages.length === 0 && activeUser.public_key && (
<div style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center',
color:'rgba(255,255,255,0.18)', fontFamily:'monospace', fontSize:11 }}>
Noch keine Nachrichten schreib als Erste(r)
</div>
)}
{messages.map(m => {
const isMine = !!m.is_mine;
const txt = decrypted[m.id];
return (
<div key={m.id} style={{ display:'flex', justifyContent: isMine ? 'flex-end' : 'flex-start',
gap:6, alignItems:'flex-end' }}>
{!isMine && (
<div style={{ width:22, height:22, borderRadius:'50%', flexShrink:0,
background:'linear-gradient(135deg,rgba(255,107,157,0.2),rgba(78,205,196,0.2))',
border:'1px solid rgba(255,255,255,0.07)',
display:'flex', alignItems:'center', justifyContent:'center' }}>
<UserIcon size={10} color="rgba(255,255,255,0.45)"/>
</div>
)}
<div style={{ maxWidth:'75%', display:'flex', flexDirection:'column',
alignItems: isMine ? 'flex-end' : 'flex-start', gap:4 }}>
<div style={{
background: isMine ? 'rgba(78,205,196,0.1)' : 'rgba(255,255,255,0.05)',
border: `1px solid ${isMine ? 'rgba(78,205,196,0.17)' : 'rgba(255,255,255,0.07)'}`,
borderRadius: isMine ? '12px 12px 3px 12px' : '12px 12px 12px 3px',
padding:'8px 12px',
}}>
{txt === undefined ? (
<span style={{ color:'rgba(255,255,255,0.2)', fontSize:12 }}></span>
) : (
<span style={{ color:'#e6e6e6', fontSize:13, fontFamily:'monospace',
lineHeight:1.55, whiteSpace:'pre-wrap', wordBreak:'break-word' }}>{txt}</span>
)}
</div>
<div style={{ display:'flex', alignItems:'center', gap:5 }}>
<span style={{ color:'rgba(255,255,255,0.2)', fontSize:9, fontFamily:'monospace' }}>
{new Date(m.created_at).toLocaleTimeString('de-DE',{ hour:'2-digit', minute:'2-digit' })}
</span>
<button onClick={() => deleteMsg(m.id)} style={{ background:'transparent', border:'none',
cursor:'pointer', padding:'0 2px', opacity:0.3, lineHeight:1,
display:'flex', alignItems:'center' }}>
<TrashIcon size={10} color="#ff6b9d"/>
</button>
</div>
</div>
</div>
);
})}
<div ref={bottomRef}/>
</div>
{/* Input */}
<div style={{ padding:'10px 14px', borderTop:'1px solid rgba(255,255,255,0.06)',
background:'#0d0d0f', flexShrink:0 }}>
{!activeUser.public_key ? (
<div style={{ color:'rgba(255,255,255,0.22)', fontSize:11, fontFamily:'monospace',
textAlign:'center', padding:'8px 0' }}>
Senden nicht möglich kein Schlüssel verfügbar
</div>
) : (
<div style={{ display:'flex', gap:8, alignItems:'flex-end' }}>
<textarea
value={text} onChange={e => setText(e.target.value)}
onKeyDown={e => { if (e.key==='Enter' && !e.shiftKey) { e.preventDefault(); send(); }}}
placeholder="Nachricht… (Enter = senden, Shift+Enter = neue Zeile)"
rows={2}
style={{ ...S.inp, resize:'none', flex:1, fontSize:13, padding:'8px 10px',
lineHeight:1.45, minHeight:42 }}
/>
<button onClick={send} disabled={sending || !text.trim()} style={{
...S.btn('#4ecdc4'), padding:'10px 16px', flexShrink:0, alignSelf:'stretch',
opacity: sending || !text.trim() ? 0.3 : 1, fontSize:17, lineHeight:1,
}}></button>
</div>
)}
</div>
</>
)}
</div>
)}
</div>
);
}