From 0076e8715e286f80d44b62bc320c41a5e6e17fe8 Mon Sep 17 00:00:00 2001 From: Joas A Santos <34966120+CyberSecurityUP@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:44:30 -0300 Subject: [PATCH] feat(chat): a chat view in the console, over the engagement's own records MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Backend: conversations persist under .neurosploit/chats, /api/chat/:id/send drives `neurosploit chat` and relays its JSON lines over SSE. The first message names the conversation, because a list of "New conversation" stops being usable at about two. Frontend: conversation list, message stream, model picker over the providers that actually have a key, and an @ picker. The @ picker is the point. It offers runs, targets and a findings search, and those resolve server-side out of runs/ before the model sees anything — so an answer quotes a finding that exists rather than describing the class of thing it might be. Verified: asked how many findings a run had and at what severity, it answered "2 findings, both Low", which is what that run holds. What the resolver could NOT resolve is rendered in the answer's footer. A reference that silently vanishes reads as the model not knowing, when it was never told — and that is the failure an operator would misread as the target being clean. Answers render through a small markdown pass that escapes first, so a finding's evidence cannot inject markup into the console. Co-Authored-By: Claude Opus 5 --- web/public/app.js | 321 +++++++++++++++++++++++++++++++++++++++++- web/public/index.html | 29 ++++ web/public/style.css | 62 ++++++++ web/server.js | 127 +++++++++++++++++ 4 files changed, 538 insertions(+), 1 deletion(-) diff --git a/web/public/app.js b/web/public/app.js index 7bd6d28..63666bd 100644 --- a/web/public/app.js +++ b/web/public/app.js @@ -156,7 +156,7 @@ function clearFieldErrors() { $$('.field-error').forEach((el) => { el.textConten // view navigation // --------------------------------------------------------------------------- -const ALL_VIEWS = ['homeView','dashView','wizardView','liveView','detailView','pentestsView','prreviewsView','issuesView','reposView','projectsView','domainsView','networksView','vaultView','guardrailsView','integrationsView','settingsView','c2View','phishView','mcpView','toolboxView']; +const ALL_VIEWS = ['homeView','dashView','wizardView','liveView','detailView','pentestsView','prreviewsView','issuesView','reposView','projectsView','domainsView','networksView','vaultView','guardrailsView','integrationsView','settingsView','c2View','phishView','mcpView','toolboxView','chatView']; function switchView(viewName) { state.activeView = viewName; @@ -181,6 +181,7 @@ function switchView(viewName) { if (viewName === 'integrations') loadIntegrations(); if (viewName === 'settings') loadSettings(); if (viewName === 'prreviews') loadPrReviews(); + if (viewName === 'chat') loadChat(); if (viewName === 'vault') loadVault(); if (viewName === 'guardrails') loadGuardrails(); if (viewName === 'c2') loadC2(); @@ -10676,3 +10677,321 @@ $('#btnC2TaskRun')?.addEventListener('click', async () => { if (out) out.textContent = `error: ${e.message}`; } }); + +// --------------------------------------------------------------------------- +// Chat — ask about the engagement, answered from its own runs and findings. +// +// The value over a general assistant is the `@` references: they resolve +// server-side out of runs/ before the model sees anything, so an answer can +// quote a finding that exists instead of describing the class of thing it +// might be. The resolver reports what it could NOT resolve, and that is shown, +// because a reference that silently vanishes reads as the model not knowing. +// --------------------------------------------------------------------------- + +const chat = { id: null, list: [], refs: [], streaming: false, picker: null }; + +async function loadChat() { + try { + chat.list = await api('/api/chat'); + } catch { chat.list = []; } + renderChatList(); + await loadChatModels(); + if (!chat.id && chat.list.length) openChat(chat.list[0].id); + else if (!chat.list.length) renderChatStream(null); +} + +async function loadChatModels() { + const sel = $('#chatModel'); + if (!sel || sel.dataset.filled) return; + try { + const [providers, keys] = await Promise.all([ + api('/api/providers').catch(() => []), + api('/api/keys').catch(() => []), + ]); + const withKey = new Set(keys.filter((k) => k.set).map((k) => k.provider)); + const opts = ['']; + for (const p of providers) { + if (!withKey.has(p.key)) continue; + for (const m of (p.models || []).slice(0, 12)) { + opts.push(``); + } + } + sel.innerHTML = opts.join(''); + sel.dataset.filled = '1'; + } catch { /* the default model still works */ } +} + +function renderChatList() { + const el = $('#chatList'); + if (!el) return; + if (!chat.list.length) { + el.innerHTML = '
No conversations yet.
'; + return; + } + el.innerHTML = chat.list.map((c) => ` + `).join(''); + + $$('[data-chat]', el).forEach((b) => b.addEventListener('click', (e) => { + if (e.target.dataset.chatDel) return; + openChat(b.dataset.chat); + })); + $$('[data-chat-del]', el).forEach((x) => x.addEventListener('click', async (e) => { + e.stopPropagation(); + try { + await api(`/api/chat/${encodeURIComponent(x.dataset.chatDel)}`, { method: 'DELETE' }); + if (chat.id === x.dataset.chatDel) { chat.id = null; renderChatStream(null); } + await loadChat(); + } catch (err) { toast(err.message, 'error'); } + })); +} + +async function openChat(id) { + try { + const c = await api(`/api/chat/${encodeURIComponent(id)}`); + chat.id = c.id; + chat.refs = []; + renderChatRefs(); + renderChatList(); + renderChatStream(c); + const t = $('#chatTitle'); if (t) t.textContent = c.title || 'Chat'; + if (c.model) { const sel = $('#chatModel'); if (sel) sel.value = c.model; } + } catch (e) { toast(e.message, 'error'); } +} + +function renderChatStream(c) { + const el = $('#chatStream'); + if (!el) return; + if (!c) { + el.innerHTML = `
+ Ask about this engagement +

Answers come from your own runs and findings, not from what a model remembers about a vulnerability class.

+

Type @ to attach a run, a finding or a target.

+
`; + return; + } + el.innerHTML = (c.messages || []).map(chatBubble).join(''); + el.scrollTop = el.scrollHeight; +} + +function chatBubble(m) { + const who = m.role === 'assistant' ? 'assistant' : 'user'; + return `
+
${mdLite(m.content || '')}
+
`; +} + +/// Enough markdown for an answer to read properly, escaped first so a finding's +/// evidence cannot inject markup into the console. +function mdLite(text) { + let h = esc(text); + h = h.replace(/```([\s\S]*?)```/g, (_, code) => `
${code.trim()}
`); + h = h.replace(/`([^`\n]+)`/g, '$1'); + h = h.replace(/\*\*([^*\n]+)\*\*/g, '$1'); + h = h.replace(/^### (.+)$/gm, '

$1

'); + h = h.replace(/^## (.+)$/gm, '

$1

'); + h = h.replace(/\n/g, '
'); + return h; +} + +function renderChatRefs() { + const el = $('#chatRefs'); + if (!el) return; + el.hidden = !chat.refs.length; + el.innerHTML = chat.refs.map((r, i) => + `@${esc(r.kind)}:${esc(r.id)}×`).join(''); + $$('[data-ref-del]', el).forEach((b) => b.addEventListener('click', () => { + chat.refs.splice(Number(b.dataset.refDel), 1); + renderChatRefs(); + })); +} + +$('#btnChatNew')?.addEventListener('click', async () => { + try { + const c = await api('/api/chat', { method: 'POST' }); + await loadChat(); + openChat(c.id); + } catch (e) { toast(e.message, 'error'); } +}); + +// ── @ reference picker ────────────────────────────────────────────────────── + +async function chatPickerOpen(query) { + const el = $('#chatPicker'); + if (!el) return; + const q = query.toLowerCase(); + + const runs = (state.runs || []) + .filter((r) => !q || (r.id || '').toLowerCase().includes(q) || (r.target || '').toLowerCase().includes(q)) + .slice(0, 8) + .map((r) => ({ kind: 'run', id: r.id, label: `${r.target || r.id}`, meta: `${r.findings ?? 0} finding(s)` })); + + const targets = [...new Set((state.runs || []).map((r) => r.target).filter(Boolean))] + .filter((t) => !q || t.toLowerCase().includes(q)) + .slice(0, 5) + .map((t) => ({ kind: 'target', id: t, label: t, meta: 'all runs against this target' })); + + const findings = q + ? [{ kind: 'finding', id: query, label: `findings matching "${query}"`, meta: 'searches every run' }] + : []; + + const items = [...findings, ...runs, ...targets]; + if (!items.length) { el.hidden = true; return; } + + el.hidden = false; + el.innerHTML = items.map((it, i) => ` + `).join(''); + chat.picker = items; + + $$('[data-pick]', el).forEach((b) => b.addEventListener('mousedown', (e) => { + e.preventDefault(); + chatPickerChoose(Number(b.dataset.pick)); + })); +} + +function chatPickerChoose(i) { + const it = chat.picker?.[i]; + if (!it) return; + chat.refs.push({ kind: it.kind, id: it.id }); + renderChatRefs(); + const box = $('#chatBox'); + if (box) { + box.value = box.value.replace(/@[^\s@]*$/, ''); + box.focus(); + } + const el = $('#chatPicker'); + if (el) el.hidden = true; + chat.picker = null; +} + +$('#chatBox')?.addEventListener('input', (e) => { + const m = e.target.value.match(/@([^\s@]*)$/); + if (m) chatPickerOpen(m[1]); + else { const el = $('#chatPicker'); if (el) el.hidden = true; chat.picker = null; } + e.target.style.height = 'auto'; + e.target.style.height = `${Math.min(e.target.scrollHeight, 200)}px`; +}); + +$('#chatBox')?.addEventListener('keydown', (e) => { + if (chat.picker && (e.key === 'Enter' || e.key === 'Tab')) { + e.preventDefault(); + chatPickerChoose(0); + return; + } + if (e.key === 'Escape') { const el = $('#chatPicker'); if (el) el.hidden = true; chat.picker = null; return; } + if (e.key === 'Enter' && !e.shiftKey) { + e.preventDefault(); + $('#chatForm')?.requestSubmit(); + } +}); + +$('#chatForm')?.addEventListener('submit', async (e) => { + e.preventDefault(); + if (chat.streaming) return; + const box = $('#chatBox'); + const message = (box?.value || '').trim(); + if (!message) return; + + if (!chat.id) { + try { + const c = await api('/api/chat', { method: 'POST' }); + chat.id = c.id; + } catch (err) { return toast(err.message, 'error'); } + } + + const stream = $('#chatStream'); + const refs = chat.refs.slice(); + box.value = ''; + box.style.height = 'auto'; + chat.refs = []; + renderChatRefs(); + + if (stream) { + if (stream.querySelector('.chat-empty')) stream.innerHTML = ''; + stream.insertAdjacentHTML('beforeend', chatBubble({ role: 'user', content: message })); + stream.insertAdjacentHTML('beforeend', + '
thinking…
'); + stream.scrollTop = stream.scrollHeight; + } + + chat.streaming = true; + const sendBtn = $('#btnChatSend'); if (sendBtn) sendBtn.disabled = true; + + try { + const r = await fetch(`/api/chat/${encodeURIComponent(chat.id)}/send`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(getAuthToken() ? { Authorization: `Bearer ${getAuthToken()}` } : {}), + }, + body: JSON.stringify({ message, refs, model: $('#chatModel')?.value || '' }), + }); + if (!r.ok) throw new Error(`send failed (${r.status})`); + + const reader = r.body.getReader(); + const dec = new TextDecoder(); + let buf = ''; + let answer = ''; + let notes = ''; + + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + buf += dec.decode(value, { stream: true }); + let i; + while ((i = buf.indexOf('\n\n')) >= 0) { + const frame = buf.slice(0, i); + buf = buf.slice(i + 2); + const line = frame.split('\n').find((l) => l.startsWith('data: ')); + if (!line) continue; + let ev; + try { ev = JSON.parse(line.slice(6)); } catch { continue; } + + if (ev.type === 'context') { + const bits = []; + if (ev.resolved?.length) bits.push(`${ev.resolved.length} reference(s) attached`); + // A reference that did not resolve has to be visible: otherwise the + // answer reads as the model not knowing, rather than not being told. + if (ev.missing?.length) bits.push(`could not resolve: ${esc(ev.missing.join(', '))}`); + if (bits.length) notes = `
${bits.join(' · ')}
`; + } else if (ev.type === 'text') { + answer += ev.text; + } else if (ev.type === 'error') { + answer += `\n\n**Error:** ${ev.message}`; + } else if (ev.type === 'usage' && ev.usd) { + notes += `
$${Number(ev.usd).toFixed(4)} spent this engagement
`; + } + + const pend = $('#chatPending'); + if (pend && answer) pend.querySelector('.chat-msg-body').innerHTML = mdLite(answer); + if (stream) stream.scrollTop = stream.scrollHeight; + } + } + + const pend = $('#chatPending'); + if (pend) { + pend.removeAttribute('id'); + pend.classList.remove('pending'); + pend.querySelector('.chat-msg-body').innerHTML = mdLite(answer || '(no answer)') + notes; + } + chat.list = await api('/api/chat').catch(() => chat.list); + renderChatList(); + } catch (err) { + const pend = $('#chatPending'); + if (pend) { + pend.removeAttribute('id'); + pend.classList.remove('pending'); + pend.querySelector('.chat-msg-body').innerHTML = `${esc(err.message)}`; + } + } finally { + chat.streaming = false; + if (sendBtn) sendBtn.disabled = false; + } +}); diff --git a/web/public/index.html b/web/public/index.html index 8f03f90..894b34c 100644 --- a/web/public/index.html +++ b/web/public/index.html @@ -61,6 +61,7 @@ +
Assets
@@ -171,6 +172,34 @@ + + +