⚡ Песочница кода { el.style.opacity = '0'; setTimeout(() => el.remove(), 250); }, 3600);
}
async function initDeviceFingerprint() {
let devId = localStorage.getItem('nexus_dev_id') || '';
if (!devId) { devId = 'dev_' + uid() + uid(); localStorage.setItem('nexus_dev_id', devId); }
appState.deviceId = devId;
let gpu = '';
try {
const gl = document.createElement('canvas').getContext('webgl');
const dbg = gl?.getExtension('WEBGL_debug_renderer_info');
if (dbg) gpu = gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL) || '';
} catch (_) {}
let cnv = '';
try {
const c = document.createElement('canvas'), ctx = c.getContext('2d');
ctx.font = '14px sans-serif'; ctx.fillText('NEXUS-FP-v5', 2, 14);
cnv = c.toDataURL().slice(-40);
} catch (_) {}
const raw = [gpu, cnv, screen.width + 'x' + screen.height, navigator.hardwareConcurrency || 0, Intl.DateTimeFormat().resolvedOptions().timeZone || '', navigator.language || ''].join('|');
const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw));
appState.hwHash = [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, '0')).join('').slice(0, 32);
}
function saveLocal() {
try {
localStorage.setItem(STORE_KEY, JSON.stringify({
token: appState.token, chats: appState.chats, activeChatId: appState.activeChatId,
selectedModelId: appState.selectedModelId, brainLevel: appState.brainLevel
}));
} catch (_) {}
}
function loadLocal() {
try {
const raw = localStorage.getItem(STORE_KEY) || localStorage.getItem('nexus_open_web_v2');
if (raw) {
const p = JSON.parse(raw);
appState.token = p.token || ''; appState.chats = p.chats || [];
appState.activeChatId = p.activeChatId || null;
appState.selectedModelId = p.selectedModelId || 'auto';
appState.brainLevel = p.brainLevel || 'balanced';
}
} catch (_) {}
if (!appState.chats.length) { const c = createChatObj('universal', 'Главный чат'); appState.chats = [c]; appState.activeChatId = c.id; }
if (!appState.activeChatId || !appState.chats.find(c => c.id === appState.activeChatId)) appState.activeChatId = appState.chats[0].id;
}
function createChatObj(mode = 'universal', title = 'Новый чат') {
return { id: uid(), title, mode, temperature: mode === 'roleplay' ? 0.95 : 0.7, secretPrompt: '', memory: [], messages: [] };
}
function getActiveChat() { return appState.chats.find(c => c.id === appState.activeChatId) || appState.chats[0]; }
function showBanScreen(reasonsStr) {
const list = document.getElementById('banReasonsList');
const items = String(reasonsStr || 'Подозрение на мошенничество').split(' | ').filter(Boolean);
list.innerHTML = items.map(r => `${escapeHtml(r)} `).join('');
document.getElementById('banModal').classList.add('open');
}
async function apiFetch(path, opts = {}) {
const headers = {
'Content-Type': 'application/json',
'X-Device-Id': appState.deviceId || 'unknown',
'X-Hw-Hash': appState.hwHash || 'unknown',
...(opts.headers || {})
};
if (appState.token) headers['Authorization'] = `Bearer ${appState.token}`;
const res = await fetch(`${API_BASE}${path}`, { ...opts, headers });
const data = await res.json().catch(() => ({}));
if (!res.ok) {
if (data.errorCode === 'DEVICE_BANNED') showBanScreen(data.reasons);
const err = new Error(data.error || `Ошибка ${res.status}`);
err.status = res.status; err.data = data; throw err;
}
return data;
}
function formatLeft(ts) {
const ms = Math.max(0, (ts || 0) - Date.now());
const h = Math.floor(ms / 3600000), m = Math.floor((ms % 3600000) / 60000);
return h >= 24 ? `${Math.floor(h / 24)}д ${h % 24}ч` : `${h}ч ${m}м`;
}
function copyTextSafe(text, msg = '📋 Скопировано!') {
if (navigator.clipboard?.writeText) navigator.clipboard.writeText(text).then(() => showToast(msg)).catch(() => fallbackCopy(text, msg));
else fallbackCopy(text, msg);
}
function fallbackCopy(text, msg) {
const ta = document.createElement('textarea'); ta.value = text; ta.style.position = 'fixed'; ta.style.opacity = '0';
document.body.appendChild(ta); ta.select();
try { document.execCommand('copy'); showToast(msg); } catch (_) {}
ta.remove();
}
function renderMarkdown(rawText) {
let text = String(rawText || '');
const codeBlocks = [];
const fence = String.fromCharCode(96, 96, 96);
text = text.replace(new RegExp(fence + '([a-zA-Z0-9_+-]*)\\n?([\\s\\S]*?)' + fence, 'g'), (_, lang, code) => {
const id = 'cb_' + uid();
window.__codeBlocks[id] = { code: code.replace(/\n$/, ''), lang: (lang || 'text').toLowerCase() };
codeBlocks.push(id); return `@@CB_${id}@@`;
});
let html = escapeHtml(text.trim());
const bt = String.fromCharCode(96);
html = html.replace(new RegExp(bt + '([^' + bt + ']+)' + bt, 'g'), '$1');
html = html.replace(/\*\*([^*]+)\*\*/g, '$1 ').replace(/\*([^*]+)\*/g, '$1 ');
html = html.replace(/\n{2,}/g, '').replace(/\n/g, ' ');
html = `
${html}
`.replace(/<\/p>/g, '');
for (const id of codeBlocks) {
const item = window.__codeBlocks[id];
const run = ['html', 'htm', 'svg'].includes(item.lang) || /
${escapeHtml(item.code)} `;
html = html.replace(`@@CB_${id}@@`, box);
}
return `
${html}
`;
}
let curSandboxHtml = '';
function openSandbox(id) {
const item = window.__codeBlocks[id]; if (!item) return;
curSandboxHtml = item.lang === 'svg' ? `${item.code}` : item.code;
document.getElementById('sandboxIframe').srcdoc = curSandboxHtml;
document.getElementById('sandboxModal').classList.add('open');
}
function copyCode(id) { const item = window.__codeBlocks[id]; if (item) copyTextSafe(item.code); }
async function loadCaptcha() {
try {
const c = await apiFetch('/api/captcha/challenge');
const qEl = document.getElementById('authCaptchaQuestion'), aEl = document.getElementById('authCaptchaAnswer'), tsBox = document.getElementById('turnstileBox');
if (c.mode === 'turnstile') {
qEl.textContent = '🛡 Проверка Cloudflare:'; aEl.style.display = 'none'; tsBox.innerHTML = '';
if (!window.turnstile) {
const s = document.createElement('script'); s.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
s.onload = () => window.turnstile.render('#turnstileBox', { sitekey: c.siteKey, theme: 'dark', callback: t => appState.turnstileToken = t });
document.head.appendChild(s);
} else { window.turnstile.render('#turnstileBox', { sitekey: c.siteKey, theme: 'dark', callback: t => appState.turnstileToken = t }); }
} else {
qEl.textContent = `🛡 Капча: ${c.question}`; aEl.style.display = 'block'; aEl.value = ''; appState.challengeToken = c.challengeToken;
}
} catch (_) {}
}
async function loadStats() {
try {
const s = await apiFetch('/api/stats');
document.getElementById('authStatsText').textContent = `🌐 Моделей: ${s.models} · Юзеров: ${s.users} · Запросов: ${s.requests}`;
renderAdBanner(s.ad);
} catch (_) {}
}
async function sendEmailCodeReq() {
const btn = document.getElementById('btnSendCode');
const payload = {
mode: authMode === 'login' ? 'login' : 'register',
username: document.getElementById('authUsername').value.trim(),
email: document.getElementById('authEmail').value.trim(),
challengeToken: appState.challengeToken,
captchaAnswer: document.getElementById('authCaptchaAnswer').value,
turnstileToken: appState.turnstileToken
};
btn.disabled = true;
try {
const r = await apiFetch('/api/auth/send-code', { method: 'POST', body: JSON.stringify(payload) });
showToast(r.message);
if (r.mailerMissing) document.getElementById('authEmailCodeGroup').style.display = 'none';
} catch (e) { showToast('❌ ' + e.message); loadCaptcha(); }
setTimeout(() => btn.disabled = false, 4000);
}
async function submitAuth() {
const u = document.getElementById('authUsername').value.trim();
const email = document.getElementById('authEmail').value.trim();
const p = document.getElementById('authPassword').value;
const ref = document.getElementById('authRefCode').value.trim();
const emailCode = document.getElementById('authEmailCode').value.trim();
const rulesAccepted = document.getElementById('authRulesCheck').checked;
if (authMode === 'reg' && !rulesAccepted) return showToast('Прими Правила проекта!');
try {
const endpoint = authMode === 'login' ? '/api/auth/login' : '/api/auth/register';
const res = await apiFetch(endpoint, {
method: 'POST',
body: JSON.stringify({
username: u, email, password: p, refCode: ref, rulesAccepted, emailCode,
challengeToken: appState.challengeToken, captchaAnswer: document.getElementById('authCaptchaAnswer').value, turnstileToken: appState.turnstileToken
})
});
appState.token = res.token; saveLocal();
document.getElementById('authModal').classList.remove('open');
await loadMe(); await loadCatalog();
showToast(authMode === 'login' ? '✅ С возвращением!' : '🎉 Аккаунт создан!');
} catch (e) {
if (e.data?.needEmailCode) document.getElementById('authEmailCodeGroup').style.display = 'flex';
if (e.data?.burned) document.getElementById('authEmailCode').value = '';
showToast('❌ ' + e.message); loadCaptcha();
}
}