CRITICAL: - #1 JWT секрет: убран fallback, fail-fast без SESSION_SECRET - #7 env leak: минимальный env для subprocess (не os.environ.copy()) HIGH: - #4 timing attack: hmac.compare_digest вместо == - #5 brute force: rate limiting 5 попыток / 5 мин на IP - #6 upload: whitelist расширений (xlsx, docx, pdf, csv, txt, xml, json, yaml) MEDIUM: - #9 XSS: textContent вместо innerHTML для имён файлов - #10 token expire: 24ч вместо 7 дней - #11 DoS: asyncio.Semaphore(3) на Claude-процессы - #12 session isolation: ключ (username, tab_id) вместо tab_id - #14 DoS: лимит длины сообщения 10000 символов - #15 OOM: чтение upload по чанкам 1MB LOW: - #19 reset endpoint: POST с body Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
356 lines
14 KiB
HTML
356 lines
14 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="ru">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>Сметный ИИ-ассистент</title>
|
||
<style>
|
||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f5f5f5; height: 100vh; display: flex; flex-direction: column; }
|
||
|
||
/* Login */
|
||
#login-screen { display: flex; align-items: center; justify-content: center; height: 100vh; }
|
||
#login-form { background: #fff; padding: 2rem; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,.1); width: 320px; }
|
||
#login-form h2 { margin-bottom: 1rem; text-align: center; }
|
||
#login-form input { width: 100%; padding: .6rem; margin-bottom: .8rem; border: 1px solid #ddd; border-radius: 6px; font-size: 1rem; }
|
||
#login-form button { width: 100%; padding: .7rem; background: #2563eb; color: #fff; border: none; border-radius: 6px; font-size: 1rem; cursor: pointer; }
|
||
#login-form button:hover { background: #1d4ed8; }
|
||
#login-error { color: #dc2626; font-size: .85rem; margin-bottom: .5rem; display: none; }
|
||
|
||
/* Chat */
|
||
#chat-screen { display: none; flex-direction: column; height: 100vh; }
|
||
#header { background: #fff; padding: .6rem 1rem; border-bottom: 1px solid #e5e7eb; display: flex; align-items: center; justify-content: space-between; }
|
||
#header h1 { font-size: 1.1rem; font-weight: 600; }
|
||
.header-actions { display: flex; gap: .5rem; }
|
||
.header-actions button { padding: .3rem .8rem; background: #f3f4f6; border: 1px solid #d1d5db; border-radius: 6px; cursor: pointer; font-size: .8rem; }
|
||
.header-actions button:hover { background: #e5e7eb; }
|
||
|
||
#messages { flex: 1; overflow-y: auto; padding: 1rem; display: flex; flex-direction: column; gap: .6rem; }
|
||
.msg { max-width: 80%; padding: .7rem 1rem; border-radius: 12px; line-height: 1.5; white-space: pre-wrap; word-break: break-word; font-size: .95rem; }
|
||
.msg-user { align-self: flex-end; background: #2563eb; color: #fff; }
|
||
.msg-ai { align-self: flex-start; background: #fff; border: 1px solid #e5e7eb; }
|
||
.msg-tool { align-self: flex-start; background: #fef3c7; border: 1px solid #fcd34d; font-size: .8rem; font-family: monospace; }
|
||
.msg-file { align-self: flex-start; background: #ecfdf5; border: 1px solid #6ee7b7; font-size: .85rem; }
|
||
.msg-file a { color: #059669; text-decoration: underline; cursor: pointer; }
|
||
.msg-error { align-self: center; background: #fef2f2; border: 1px solid #fca5a5; color: #dc2626; }
|
||
.msg-system { align-self: center; background: #f0f9ff; border: 1px solid #93c5fd; font-size: .8rem; color: #1e40af; }
|
||
.typing { align-self: flex-start; color: #9ca3af; font-style: italic; font-size: .85rem; }
|
||
|
||
/* Input */
|
||
#input-area { background: #fff; border-top: 1px solid #e5e7eb; padding: .8rem 1rem; }
|
||
#drop-zone { border: 2px dashed transparent; border-radius: 8px; transition: border-color .2s; padding: .3rem; }
|
||
#drop-zone.dragover { border-color: #2563eb; background: #eff6ff; }
|
||
#file-list { display: flex; gap: .3rem; flex-wrap: wrap; margin-bottom: .3rem; }
|
||
.file-badge { background: #e0f2fe; padding: .2rem .5rem; border-radius: 4px; font-size: .75rem; display: flex; align-items: center; gap: .3rem; }
|
||
.file-badge .remove { cursor: pointer; color: #dc2626; font-weight: bold; }
|
||
#input-row { display: flex; gap: .5rem; }
|
||
#msg-input { flex: 1; padding: .6rem; border: 1px solid #d1d5db; border-radius: 8px; font-size: 1rem; resize: none; min-height: 42px; max-height: 150px; font-family: inherit; }
|
||
#send-btn { padding: .6rem 1.2rem; background: #2563eb; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-size: 1rem; white-space: nowrap; }
|
||
#send-btn:disabled { background: #93c5fd; cursor: not-allowed; }
|
||
#file-btn { padding: .6rem; background: #f3f4f6; border: 1px solid #d1d5db; border-radius: 8px; cursor: pointer; font-size: 1.1rem; }
|
||
</style>
|
||
</head>
|
||
<body>
|
||
|
||
<!-- Login Screen -->
|
||
<div id="login-screen">
|
||
<form id="login-form" onsubmit="return doLogin(event)">
|
||
<h2>Сметный ИИ</h2>
|
||
<div id="login-error">Неверный логин или пароль</div>
|
||
<input type="text" id="login-user" placeholder="Логин" autocomplete="username" required>
|
||
<input type="password" id="login-pass" placeholder="Пароль" autocomplete="current-password" required>
|
||
<button type="submit">Войти</button>
|
||
</form>
|
||
</div>
|
||
|
||
<!-- Chat Screen -->
|
||
<div id="chat-screen">
|
||
<div id="header">
|
||
<h1>Сметный ИИ-ассистент</h1>
|
||
<div class="header-actions">
|
||
<button onclick="resetSession()">Новый диалог</button>
|
||
<button onclick="listFiles()">Файлы</button>
|
||
<button onclick="logout()">Выйти</button>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="messages"></div>
|
||
|
||
<div id="input-area">
|
||
<div id="drop-zone">
|
||
<div id="file-list"></div>
|
||
<div id="input-row">
|
||
<button id="file-btn" onclick="document.getElementById('file-input').click()" title="Прикрепить файл">📎</button>
|
||
<textarea id="msg-input" placeholder="Напишите сообщение..." rows="1" onkeydown="handleKey(event)"></textarea>
|
||
<button id="send-btn" onclick="sendMessage()">Отправить</button>
|
||
</div>
|
||
</div>
|
||
<input type="file" id="file-input" multiple hidden onchange="handleFiles(this.files)">
|
||
</div>
|
||
</div>
|
||
|
||
<script>
|
||
const API = '';
|
||
let token = localStorage.getItem('token');
|
||
let pendingFiles = [];
|
||
let streaming = false;
|
||
// Each tab gets its own session — allows multiple windows
|
||
const tabId = sessionStorage.getItem('tabId') || crypto.randomUUID();
|
||
sessionStorage.setItem('tabId', tabId);
|
||
|
||
// --- Init ---
|
||
if (token) showChat(); else showLogin();
|
||
|
||
function showLogin() {
|
||
document.getElementById('login-screen').style.display = 'flex';
|
||
document.getElementById('chat-screen').style.display = 'none';
|
||
}
|
||
function showChat() {
|
||
document.getElementById('login-screen').style.display = 'none';
|
||
document.getElementById('chat-screen').style.display = 'flex';
|
||
document.getElementById('msg-input').focus();
|
||
}
|
||
|
||
// --- Auth ---
|
||
async function doLogin(e) {
|
||
e.preventDefault();
|
||
const user = document.getElementById('login-user').value;
|
||
const pass = document.getElementById('login-pass').value;
|
||
try {
|
||
const r = await fetch(API + '/api/login', {
|
||
method: 'POST',
|
||
headers: {'Content-Type': 'application/json'},
|
||
body: JSON.stringify({username: user, password: pass})
|
||
});
|
||
if (!r.ok) throw new Error();
|
||
const data = await r.json();
|
||
token = data.token;
|
||
localStorage.setItem('token', token);
|
||
showChat();
|
||
addMsg('system', 'Добро пожаловать! Напишите вопрос или прикрепите файл.');
|
||
} catch {
|
||
document.getElementById('login-error').style.display = 'block';
|
||
}
|
||
return false;
|
||
}
|
||
function logout() {
|
||
token = null;
|
||
localStorage.removeItem('token');
|
||
showLogin();
|
||
}
|
||
function authHeaders() {
|
||
return {'Authorization': 'Bearer ' + token, 'X-Tab-Id': tabId};
|
||
}
|
||
|
||
// --- Messages ---
|
||
const msgs = document.getElementById('messages');
|
||
function addMsg(type, text) {
|
||
const div = document.createElement('div');
|
||
div.className = 'msg msg-' + type;
|
||
div.textContent = text;
|
||
msgs.appendChild(div);
|
||
msgs.scrollTop = msgs.scrollHeight;
|
||
return div;
|
||
}
|
||
function addTyping() {
|
||
const div = document.createElement('div');
|
||
div.className = 'typing';
|
||
div.id = 'typing-indicator';
|
||
div.textContent = 'Claude думает...';
|
||
msgs.appendChild(div);
|
||
msgs.scrollTop = msgs.scrollHeight;
|
||
return div;
|
||
}
|
||
function removeTyping() {
|
||
const el = document.getElementById('typing-indicator');
|
||
if (el) el.remove();
|
||
}
|
||
|
||
// --- File Upload ---
|
||
const dropZone = document.getElementById('drop-zone');
|
||
dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('dragover'); });
|
||
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover'));
|
||
dropZone.addEventListener('drop', e => {
|
||
e.preventDefault();
|
||
dropZone.classList.remove('dragover');
|
||
handleFiles(e.dataTransfer.files);
|
||
});
|
||
|
||
function handleFiles(fileList) {
|
||
for (const f of fileList) pendingFiles.push(f);
|
||
renderFileList();
|
||
}
|
||
function renderFileList() {
|
||
const fl = document.getElementById('file-list');
|
||
fl.innerHTML = '';
|
||
pendingFiles.forEach((f, i) => {
|
||
const badge = document.createElement('span');
|
||
badge.className = 'file-badge';
|
||
badge.textContent = f.name + ' ';
|
||
const rm = document.createElement('span');
|
||
rm.className = 'remove';
|
||
rm.textContent = '×';
|
||
rm.onclick = () => removeFile(i);
|
||
badge.appendChild(rm);
|
||
fl.appendChild(badge);
|
||
});
|
||
}
|
||
function removeFile(i) { pendingFiles.splice(i, 1); renderFileList(); }
|
||
|
||
async function uploadFiles() {
|
||
const uploaded = [];
|
||
for (const f of pendingFiles) {
|
||
const fd = new FormData();
|
||
fd.append('file', f);
|
||
const r = await fetch(API + '/api/upload', {
|
||
method: 'POST',
|
||
headers: authHeaders(),
|
||
body: fd,
|
||
});
|
||
if (r.ok) {
|
||
const data = await r.json();
|
||
uploaded.push(data.filename);
|
||
}
|
||
}
|
||
pendingFiles = [];
|
||
renderFileList();
|
||
return uploaded;
|
||
}
|
||
|
||
// --- Send Message ---
|
||
function handleKey(e) {
|
||
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
|
||
}
|
||
|
||
async function sendMessage() {
|
||
if (streaming) return;
|
||
const input = document.getElementById('msg-input');
|
||
let text = input.value.trim();
|
||
if (!text && pendingFiles.length === 0) return;
|
||
|
||
// Upload files first
|
||
let uploaded = [];
|
||
if (pendingFiles.length > 0) {
|
||
uploaded = await uploadFiles();
|
||
if (uploaded.length > 0) {
|
||
const fileNote = 'Загружены файлы: ' + uploaded.join(', ');
|
||
addMsg('file', fileNote);
|
||
if (!text) text = 'Я загрузил файлы: ' + uploaded.join(', ') + '. Покажи их содержимое.';
|
||
else text = 'Файлы в рабочей директории: ' + uploaded.join(', ') + '\n\n' + text;
|
||
}
|
||
}
|
||
|
||
addMsg('user', text);
|
||
input.value = '';
|
||
input.style.height = 'auto';
|
||
|
||
streaming = true;
|
||
document.getElementById('send-btn').disabled = true;
|
||
addTyping();
|
||
|
||
try {
|
||
const r = await fetch(API + '/api/chat', {
|
||
method: 'POST',
|
||
headers: {...authHeaders(), 'Content-Type': 'application/json'},
|
||
body: JSON.stringify({message: text}),
|
||
});
|
||
|
||
if (r.status === 401) { logout(); return; }
|
||
if (!r.ok) { addMsg('error', 'Ошибка: ' + r.status); return; }
|
||
|
||
removeTyping();
|
||
let aiDiv = null;
|
||
let aiText = '';
|
||
const reader = r.body.getReader();
|
||
const decoder = new TextDecoder();
|
||
let buffer = '';
|
||
|
||
while (true) {
|
||
const {done, value} = await reader.read();
|
||
if (done) break;
|
||
buffer += decoder.decode(value, {stream: true});
|
||
|
||
const lines = buffer.split('\n');
|
||
buffer = lines.pop();
|
||
|
||
let eventType = '';
|
||
for (const line of lines) {
|
||
if (line.startsWith('event: ')) {
|
||
eventType = line.slice(7);
|
||
} else if (line.startsWith('data: ')) {
|
||
const data = JSON.parse(line.slice(6));
|
||
if (eventType === 'text') {
|
||
if (!aiDiv) aiDiv = addMsg('ai', '');
|
||
aiText += data.text;
|
||
aiDiv.textContent = aiText;
|
||
msgs.scrollTop = msgs.scrollHeight;
|
||
} else if (eventType === 'tool') {
|
||
// Show minimal status, not raw code
|
||
const toolNames = {Bash: 'Выполняю...', Read: 'Читаю файл...', Write: 'Создаю файл...', Edit: 'Редактирую...', Glob: 'Ищу файлы...', Grep: 'Ищу в файлах...'};
|
||
const label = toolNames[data.tool] || 'Обрабатываю...';
|
||
removeTyping();
|
||
addTyping().textContent = label;
|
||
} else if (eventType === 'done') {
|
||
removeTyping();
|
||
// Always show final result if we haven't shown text yet
|
||
if (!aiText && data.result) {
|
||
aiDiv = addMsg('ai', data.result);
|
||
}
|
||
}
|
||
eventType = '';
|
||
}
|
||
}
|
||
}
|
||
if (!aiDiv && !aiText) addMsg('ai', '(пустой ответ)');
|
||
|
||
} catch (err) {
|
||
removeTyping();
|
||
addMsg('error', 'Ошибка соединения: ' + err.message);
|
||
} finally {
|
||
streaming = false;
|
||
document.getElementById('send-btn').disabled = false;
|
||
input.focus();
|
||
}
|
||
}
|
||
|
||
// --- Session ---
|
||
async function resetSession() {
|
||
await fetch(API + '/api/reset', {method: 'POST', headers: {...authHeaders(), 'Content-Type': 'application/json'}, body: '{}'});
|
||
msgs.innerHTML = '';
|
||
addMsg('system', 'Новый диалог начат.');
|
||
}
|
||
|
||
async function listFiles() {
|
||
const r = await fetch(API + '/api/files', {headers: authHeaders()});
|
||
if (!r.ok) return;
|
||
const files = await r.json();
|
||
if (files.length === 0) { addMsg('system', 'Файлов нет.'); return; }
|
||
const list = files.map(f => {
|
||
const kb = (f.size / 1024).toFixed(1);
|
||
return f.name + ' (' + kb + ' KB)';
|
||
}).join('\n');
|
||
const div = addMsg('file', 'Файлы в рабочей директории:\n' + list);
|
||
// Add download links
|
||
files.forEach(f => {
|
||
const a = document.createElement('a');
|
||
a.textContent = ' [скачать ' + f.name + ']';
|
||
a.href = API + '/api/files/' + encodeURIComponent(f.name);
|
||
a.onclick = e => {
|
||
e.preventDefault();
|
||
fetch(a.href, {headers: authHeaders()})
|
||
.then(r => r.blob())
|
||
.then(b => { const u = URL.createObjectURL(b); const l = document.createElement('a'); l.href = u; l.download = f.name; l.click(); });
|
||
};
|
||
div.appendChild(a);
|
||
});
|
||
}
|
||
|
||
// Auto-resize textarea
|
||
document.getElementById('msg-input').addEventListener('input', function() {
|
||
this.style.height = 'auto';
|
||
this.style.height = Math.min(this.scrollHeight, 150) + 'px';
|
||
});
|
||
</script>
|
||
</body>
|
||
</html>
|