diff --git a/app/api/v1/public_api/__init__.py b/app/api/v1/public_api/__init__.py index 0190889b..56f71599 100644 --- a/app/api/v1/public_api/__init__.py +++ b/app/api/v1/public_api/__init__.py @@ -1,13 +1,16 @@ """Public API router (public_key protected).""" -from fastapi import APIRouter +from fastapi import APIRouter, Depends +from app.api.v1.chat import router as chat_router from app.api.v1.public_api.imagine import router as imagine_router from app.api.v1.public_api.video import router as video_router from app.api.v1.public_api.voice import router as voice_router +from app.core.auth import verify_public_key router = APIRouter() +router.include_router(chat_router, dependencies=[Depends(verify_public_key)]) router.include_router(imagine_router) router.include_router(video_router) router.include_router(voice_router) diff --git a/app/core/auth.py b/app/core/auth.py index 2cb45820..e2e31297 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -2,6 +2,7 @@ API 认证模块 """ +import hashlib from typing import Optional from fastapi import HTTPException, status, Security from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials @@ -53,6 +54,27 @@ def is_public_enabled() -> bool: return bool(get_config("app.public_enabled", DEFAULT_PUBLIC_ENABLED)) +def _hash_public_key(key: str) -> str: + """计算 public_key 的 SHA-256 哈希,与前端 hashPublicKey 保持一致。""" + return hashlib.sha256(f"grok2api-public:{key}".encode()).hexdigest() + + +def _match_public_key(credentials: str, public_key: str) -> bool: + """检查凭证是否匹配 public_key(支持原始值和 public- 哈希格式)。""" + if not public_key: + return False + normalized = public_key.strip() + if not normalized: + return False + if credentials == normalized: + return True + if credentials.startswith("public-"): + expected_hash = _hash_public_key(normalized) + if credentials == f"public-{expected_hash}": + return True + return False + + async def verify_api_key( auth: Optional[HTTPAuthorizationCredentials] = Security(security), ) -> Optional[str]: @@ -72,14 +94,15 @@ async def verify_api_key( headers={"WWW-Authenticate": "Bearer"}, ) - if auth.credentials != api_key: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid authentication token", - headers={"WWW-Authenticate": "Bearer"}, - ) + # 标准 api_key 验证 + if auth.credentials == api_key: + return auth.credentials - return auth.credentials + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid authentication token", + headers={"WWW-Authenticate": "Bearer"}, + ) async def verify_app_key( @@ -143,11 +166,11 @@ async def verify_public_key( headers={"WWW-Authenticate": "Bearer"}, ) - if auth.credentials != public_key: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid authentication token", - headers={"WWW-Authenticate": "Bearer"}, - ) + if _match_public_key(auth.credentials, public_key): + return auth.credentials - return auth.credentials + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid authentication token", + headers={"WWW-Authenticate": "Bearer"}, + ) diff --git a/app/static/admin/pages/cache.html b/app/static/admin/pages/cache.html index 295ce105..94bba800 100644 --- a/app/static/admin/pages/cache.html +++ b/app/static/admin/pages/cache.html @@ -9,8 +9,8 @@ - - + + @@ -196,12 +196,12 @@ - - - - + + + + - + diff --git a/app/static/admin/pages/config.html b/app/static/admin/pages/config.html index f59cc9df..ea3963bf 100644 --- a/app/static/admin/pages/config.html +++ b/app/static/admin/pages/config.html @@ -9,8 +9,8 @@ - - + + @@ -46,11 +46,11 @@ - - - + + + - + diff --git a/app/static/admin/pages/login.html b/app/static/admin/pages/login.html index 95a43ad1..f7ed9f40 100644 --- a/app/static/admin/pages/login.html +++ b/app/static/admin/pages/login.html @@ -24,8 +24,8 @@ } } - - + + @@ -55,10 +55,10 @@ - + - - + + diff --git a/app/static/admin/pages/token.html b/app/static/admin/pages/token.html index ff3a968f..0a9049d1 100644 --- a/app/static/admin/pages/token.html +++ b/app/static/admin/pages/token.html @@ -9,8 +9,8 @@ - - + + @@ -295,12 +295,12 @@ - - - - + + + + - + diff --git a/app/static/common/css/common.css b/app/static/common/css/common.css index bcc422af..def44185 100644 --- a/app/static/common/css/common.css +++ b/app/static/common/css/common.css @@ -355,3 +355,54 @@ td.table-empty { color: var(--accents-4); margin-top: 2px; } + +@media (max-width: 720px) { + #app-header nav > div { + padding-left: 12px; + padding-right: 12px; + gap: 8px; + } + + #app-header nav > div > div:first-child { + gap: 6px; + min-width: 0; + overflow-x: auto; + -webkit-overflow-scrolling: touch; + scrollbar-width: none; + } + + #app-header nav > div > div:first-child::-webkit-scrollbar { + display: none; + } + + #app-header .nav-link { + white-space: nowrap; + font-size: 12px; + } + + #app-header .brand-link span { + display: none; + } + + #app-header nav > div > div:first-child > .h-4 { + display: none; + } + + .nav-actions { + flex-shrink: 0; + gap: 6px; + } + + .nav-action-btn { + font-size: 10px; + padding: 0 6px; + height: 22px; + } + + .app-footer { + right: 12px; + left: 12px; + text-align: center; + font-size: 11px; + } +} diff --git a/app/static/common/js/admin-auth.js b/app/static/common/js/admin-auth.js index 36898d01..4022c06c 100644 --- a/app/static/common/js/admin-auth.js +++ b/app/static/common/js/admin-auth.js @@ -178,6 +178,13 @@ async function ensureAdminKey() { } } +async function hashPublicKey(key) { + if (!crypto?.subtle) return null; + const data = new TextEncoder().encode('grok2api-public:' + key); + const buf = await crypto.subtle.digest('SHA-256', data); + return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, '0')).join(''); +} + async function ensurePublicKey() { if (cachedPublicKey !== null) return cachedPublicKey; @@ -195,14 +202,11 @@ async function ensurePublicKey() { return null; } - if (!key) { - return null; - } - try { const ok = await verifyKey('/v1/public/verify', key); if (!ok) throw new Error('Unauthorized'); - cachedPublicKey = `Bearer ${key}`; + const hash = await hashPublicKey(key); + cachedPublicKey = hash ? `Bearer public-${hash}` : `Bearer ${key}`; return cachedPublicKey; } catch (e) { clearStoredPublicKey(); diff --git a/app/static/common/js/footer.js b/app/static/common/js/footer.js index 0fa67ce4..771fbe02 100644 --- a/app/static/common/js/footer.js +++ b/app/static/common/js/footer.js @@ -2,7 +2,7 @@ async function loadAdminFooter() { const container = document.getElementById('app-footer'); if (!container) return; try { - const res = await fetch('/static/common/html/footer.html?v=1.5.0'); + const res = await fetch('/static/common/html/footer.html?v=1.5.1'); if (!res.ok) return; container.innerHTML = await res.text(); } catch (e) { diff --git a/app/static/common/js/header.js b/app/static/common/js/header.js index f6525559..09dffb6a 100644 --- a/app/static/common/js/header.js +++ b/app/static/common/js/header.js @@ -2,7 +2,7 @@ async function loadAdminHeader() { const container = document.getElementById('app-header'); if (!container) return; try { - const res = await fetch('/static/common/html/header.html?v=1.5.0'); + const res = await fetch('/static/common/html/header.html?v=1.5.1'); if (!res.ok) return; container.innerHTML = await res.text(); const path = window.location.pathname; diff --git a/app/static/common/js/public-header.js b/app/static/common/js/public-header.js index 7dd58dc7..5b9eee8a 100644 --- a/app/static/common/js/public-header.js +++ b/app/static/common/js/public-header.js @@ -2,7 +2,7 @@ async function loadPublicHeader() { const container = document.getElementById('app-header'); if (!container) return; try { - const res = await fetch('/static/common/html/public-header.html?v=1.5.0'); + const res = await fetch('/static/common/html/public-header.html?v=1.5.1'); if (!res.ok) return; container.innerHTML = await res.text(); const logoutBtn = container.querySelector('#public-logout-btn'); diff --git a/app/static/public/css/chat.css b/app/static/public/css/chat.css index 2fdc4d35..40fac00a 100644 --- a/app/static/public/css/chat.css +++ b/app/static/public/css/chat.css @@ -142,7 +142,7 @@ body { .message-row.user .message-bubble { background: #efeeea; padding: 12px 16px; - border-radius: 999px; + border-radius: 16px; border: 1px solid var(--chat-border); } @@ -211,12 +211,48 @@ body { margin: 6px 0; } +.message-content.rendered blockquote { + margin: 8px 0; + padding: 6px 12px; + border-left: 3px solid var(--chat-border); + border-radius: 8px; + background: #f7f6f3; + color: var(--accents-5); +} + +.message-content.rendered blockquote p { + margin: 6px 0; +} + +.message-content.rendered hr { + border: none; + border-top: 1px solid var(--chat-border); + margin: 12px 0; +} + .message-content.rendered ul, .message-content.rendered ol { margin: 6px 0 10px; padding-left: 20px; } +.message-content.rendered ul.task-list { + list-style: none; + padding-left: 12px; +} + +.message-content.rendered .task-item { + display: flex; + align-items: center; + gap: 6px; +} + +.message-content.rendered .task-item input { + width: 14px; + height: 14px; + accent-color: #111; +} + .message-content.rendered li { margin: 4px 0; } @@ -781,3 +817,331 @@ body { width: 92vw; } } + +/* --- Extensions for multi-session UI --- */ +.chat-layout { + display: flex; + gap: 20px; + align-items: flex-start; +} + +.chat-sidebar { + width: 180px; + flex-shrink: 0; + border: 1px solid var(--chat-border); + border-radius: 16px; + background: var(--chat-surface); + display: flex; + flex-direction: column; + overflow: hidden; + height: calc(100vh - 56px - 64px); + position: sticky; + top: 56px; +} + +.sidebar-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 4px 12px; + border-bottom: 1px solid var(--chat-border); + min-height: 26px; +} + +.sidebar-title { + font-size: 12px; + font-weight: 600; + color: var(--chat-ink); +} + +.sidebar-actions { + display: inline-flex; + align-items: center; + gap: 8px; +} + +.sidebar-action-btn { + border: none; + background: transparent; + color: var(--chat-ink); + font-size: 10px; + padding: 0; + cursor: pointer; +} + +.sidebar-action-btn.icon-btn { + width: 24px; + height: 24px; + border-radius: 8px; + display: inline-flex; + align-items: center; + justify-content: center; +} + +.sidebar-action-btn.icon-btn:hover { + background: var(--chat-muted); +} + +.sidebar-list { + flex: 1; + overflow-y: auto; + padding: 8px; + display: flex; + flex-direction: column; + gap: 4px; +} + +.session-item { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 4px 6px; + border-radius: 10px; + cursor: pointer; +} + +.session-item:hover { + background: var(--chat-muted); +} + +.session-item.active { + background: var(--chat-soft); +} + +.session-title { + flex: 1; + min-width: 0; + font-size: 11px; + color: var(--chat-ink); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + line-height: 1.1; +} + +.session-delete { + width: 22px; + height: 22px; + border: none; + background: transparent; + color: var(--accents-4); + border-radius: 6px; + cursor: pointer; + opacity: 0; + display: inline-flex; + align-items: center; + justify-content: center; + line-height: 1; + padding: 0; +} + +.session-item:hover .session-delete { + opacity: 1; +} + +.session-delete:hover { + color: #b91c1c; + background: rgba(185, 28, 28, 0.08); +} + +.session-rename-input { + flex: 1; + min-width: 0; + font-size: 12px; + color: var(--chat-ink); + border: 1px solid var(--chat-border); + border-radius: 6px; + padding: 2px 6px; + background: var(--chat-surface); + outline: none; +} + +.session-unread { + width: 8px; + height: 8px; + border-radius: 999px; + background: #22c55e; +} + +.sidebar-overlay { + display: none; +} + +.sidebar-toggle { + display: none; + width: 30px; + height: 30px; + border-radius: 8px; + border: 1px solid var(--chat-border); + background: var(--chat-surface); + color: var(--chat-ink); + align-items: center; + justify-content: center; + cursor: pointer; +} + +.sidebar-expand-btn { + display: none; + align-self: flex-start; + border: 1px solid var(--chat-border); + background: var(--chat-surface); + color: var(--chat-ink); + padding: 0; + width: 32px; + height: 32px; + border-radius: 999px; + cursor: pointer; + margin-top: 6px; + margin-left: 0; + align-items: center; + justify-content: center; + position: sticky; + top: 56px; + z-index: 5; +} + +.sidebar-expand-btn:hover { + border-color: #b8b8b8; + background: var(--chat-muted); +} + +@media (min-width: 1025px) { +.chat-layout.collapsed { + gap: 8px; +} + + .chat-layout.collapsed .chat-sidebar { + width: 0; + border: none; + padding: 0; + overflow: hidden; + } + + .chat-layout.collapsed .chat-shell { + padding-left: 0; + } + +.chat-layout.collapsed .sidebar-expand-btn { + display: inline-flex; + margin-left: 0; + margin-right: 8px; +} +} + +.chat-shell { + flex: 1; + min-width: 0; +} + +.model-chip { + cursor: pointer; + position: relative; +} + +.model-chip:hover { + border-color: #b8b8b8; +} + +.model-label { + font-size: 12px; + color: var(--chat-ink); +} + +.model-dropdown { + position: absolute; + bottom: calc(100% + 6px); + left: 0; + min-width: 160px; + background: var(--chat-surface); + border: 1px solid var(--chat-border); + border-radius: 12px; + box-shadow: 0 10px 30px rgba(15, 15, 15, 0.08); + padding: 6px; + z-index: 20; +} + +.model-option { + padding: 6px 8px; + border-radius: 8px; + font-size: 12px; + color: var(--chat-ink); + cursor: pointer; +} + +.model-option:hover, +.model-option.selected { + background: var(--chat-muted); +} + +.action-icon-btn { + width: 34px; + height: 34px; + border-radius: 10px; + border: 1px solid var(--chat-border); + background: var(--chat-surface); + color: var(--chat-ink); + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; +} + +.action-icon-btn:hover { + border-color: #b8b8b8; +} + +.edit-msg-input { + width: 100%; + border: 1px solid var(--chat-border); + border-radius: 12px; + padding: 10px 12px; + font-size: 13px; + font-family: 'Geist Sans', sans-serif; +} + +.edit-msg-actions { + display: flex; + gap: 8px; + margin-top: 8px; +} + +@media (max-width: 1024px) { + .chat-layout { + position: relative; + } + + .chat-sidebar { + position: fixed; + top: 56px; + left: 0; + height: calc(100% - 56px); + transform: translateX(-110%); + transition: transform 0.2s ease; + z-index: 50; + } + + .chat-sidebar.open { + transform: translateX(0); + } + + .sidebar-overlay { + display: block; + position: fixed; + inset: 0; + background: rgba(17, 17, 17, 0.18); + opacity: 0; + pointer-events: none; + transition: opacity 0.2s ease; + z-index: 40; + } + + .sidebar-overlay.open { + opacity: 1; + pointer-events: auto; + } + + .sidebar-toggle { + display: inline-flex; + } +} diff --git a/app/static/public/js/chat.js b/app/static/public/js/chat.js index 126b9f01..bdc5a0fe 100644 --- a/app/static/public/js/chat.js +++ b/app/static/public/js/chat.js @@ -1,6 +1,9 @@ (() => { - const modelSelect = document.getElementById('modelSelect'); - const reasoningSelect = document.getElementById('reasoningSelect'); + const modelChip = document.getElementById('modelChip'); + const modelLabel = document.getElementById('modelLabel'); + const modelDropdown = document.getElementById('modelDropdown'); + let modelValue = 'grok-4.20-beta'; + let modelList = []; const tempRange = document.getElementById('tempRange'); const tempValue = document.getElementById('tempValue'); const topPRange = document.getElementById('topPRange'); @@ -18,12 +21,378 @@ const fileBadge = document.getElementById('fileBadge'); const fileName = document.getElementById('fileName'); const fileRemoveBtn = document.getElementById('fileRemoveBtn'); + const chatSidebar = document.getElementById('chatSidebar'); + const sidebarOverlay = document.getElementById('sidebarOverlay'); + const sidebarToggle = document.getElementById('sidebarToggle'); + const newChatBtn = document.getElementById('newChatBtn'); + const collapseSidebarBtn = document.getElementById('collapseSidebarBtn'); + const sidebarExpandBtn = document.getElementById('sidebarExpandBtn'); + const sessionListEl = document.getElementById('sessionList'); + + const STORAGE_KEY = 'grok2api_chat_sessions'; + const SIDEBAR_STATE_KEY = 'grok2api_chat_sidebar_collapsed'; + const MAX_CONTEXT_MESSAGES = 5; let messageHistory = []; let isSending = false; let abortController = null; let attachment = null; + let activeStreamInfo = null; const feedbackUrl = 'https://github.com/chenyme/grok2api/issues/new'; + const CHAT_COMPLETIONS_ENDPOINT = '/v1/public/chat/completions'; + + let sessionsData = null; + + function generateId() { + return crypto.randomUUID ? crypto.randomUUID() : Date.now().toString(36) + Math.random().toString(36).slice(2); + } + + function loadSessions() { + try { + const raw = localStorage.getItem(STORAGE_KEY); + if (raw) { + sessionsData = JSON.parse(raw); + if (!sessionsData || !Array.isArray(sessionsData.sessions)) { + sessionsData = null; + } + } + } catch (e) { + sessionsData = null; + } + if (!sessionsData || !sessionsData.sessions.length) { + const id = generateId(); + sessionsData = { + activeId: id, + sessions: [{ + id, + title: '新会话', + createdAt: Date.now(), + updatedAt: Date.now(), + messages: [] + }] + }; + saveSessions(); + } + if (!sessionsData.activeId || !sessionsData.sessions.find(s => s.id === sessionsData.activeId)) { + sessionsData.activeId = sessionsData.sessions[0].id; + } + restoreActiveSession(); + renderSessionList(); + } + + function getMessageDisplay(msg) { + if (!msg) return ''; + if (typeof msg.content === 'string') return msg.content; + if (typeof msg.display === 'string' && msg.display.trim()) return msg.display; + if (Array.isArray(msg.content)) { + const textParts = []; + let hasFile = false; + for (const block of msg.content) { + if (!block) continue; + if (block.type === 'text' && block.text) { + textParts.push(block.text); + } + if (block.type === 'file') { + hasFile = true; + } + } + const name = msg.attachmentName || ''; + const fileLabel = hasFile ? (name ? `[文件] ${name}` : '[文件]') : ''; + if (textParts.length && fileLabel) return `${textParts.join('\n')}\n${fileLabel}`; + if (textParts.length) return textParts.join('\n'); + return fileLabel || '[复合内容]'; + } + return '[复合内容]'; + } + + function serializeMessage(msg) { + if (!msg || typeof msg !== 'object') return msg; + if (Array.isArray(msg.content)) { + return { + ...msg, + content: getMessageDisplay(msg) + }; + } + return msg; + } + + function serializeSessions() { + if (!sessionsData) return null; + return { + activeId: sessionsData.activeId, + sessions: sessionsData.sessions.map((session) => ({ + ...session, + messages: Array.isArray(session.messages) + ? session.messages.map(serializeMessage) + : [] + })) + }; + } + + function saveSessions() { + if (!sessionsData) return; + const snapshot = serializeSessions(); + if (!snapshot) return; + try { + localStorage.setItem(STORAGE_KEY, JSON.stringify(snapshot)); + } catch (e) { + toast('本地存储空间不足,部分会话未保存', 'error'); + } + } + + function trimMessageHistory(maxCount = MAX_CONTEXT_MESSAGES) { + if (!maxCount || maxCount <= 0) return; + if (messageHistory.length <= maxCount) return; + messageHistory = messageHistory.slice(-maxCount); + const session = getActiveSession(); + if (session) { + session.messages = messageHistory.slice(); + session.updatedAt = Date.now(); + saveSessions(); + renderSessionList(); + } + if (chatLog) { + const rows = Array.from(chatLog.querySelectorAll('.message-row')); + const removeCount = rows.length - messageHistory.length; + if (removeCount > 0) { + rows.slice(0, removeCount).forEach((row) => row.remove()); + } + } + if (!messageHistory.length) { + showEmptyState(); + } + } + + function getActiveSession() { + if (!sessionsData) return null; + return sessionsData.sessions.find(s => s.id === sessionsData.activeId) || null; + } + + function restoreActiveSession() { + const session = getActiveSession(); + if (!session) return; + messageHistory = session.messages.slice(); + trimMessageHistory(); + if (chatLog) chatLog.innerHTML = ''; + if (!messageHistory.length) { + showEmptyState(); + return; + } + hideEmptyState(); + for (const msg of messageHistory) { + const displayContent = getMessageDisplay(msg); + const editable = !msg.hasAttachment && typeof msg.content === 'string'; + const entry = createMessage(msg.role, displayContent, true, { editable }); + if (entry && msg.role === 'assistant') { + updateMessage(entry, displayContent, true); + } + } + if (activeStreamInfo && activeStreamInfo.sessionId === session.id && activeStreamInfo.entry.row) { + chatLog.appendChild(activeStreamInfo.entry.row); + } + scrollToBottom(); + } + + function createSession() { + const id = generateId(); + const session = { + id, + title: '新会话', + createdAt: Date.now(), + updatedAt: Date.now(), + messages: [] + }; + sessionsData.sessions.unshift(session); + sessionsData.activeId = id; + messageHistory = []; + if (chatLog) chatLog.innerHTML = ''; + showEmptyState(); + saveSessions(); + renderSessionList(); + if (isMobileSidebar()) closeSidebar(); + } + + function deleteSession(id) { + const idx = sessionsData.sessions.findIndex(s => s.id === id); + if (idx === -1) return; + sessionsData.sessions.splice(idx, 1); + if (!sessionsData.sessions.length) { + createSession(); + return; + } + if (sessionsData.activeId === id) { + const newIdx = Math.min(idx, sessionsData.sessions.length - 1); + sessionsData.activeId = sessionsData.sessions[newIdx].id; + restoreActiveSession(); + } + saveSessions(); + renderSessionList(); + } + + function switchSession(id) { + if (sessionsData.activeId === id) return; + syncCurrentSession(); + syncSessionModel(); + sessionsData.activeId = id; + const target = getActiveSession(); + if (target) target.unread = false; + restoreActiveSession(); + restoreSessionModel(); + saveSessions(); + renderSessionList(); + if (isMobileSidebar()) closeSidebar(); + } + + function syncCurrentSession() { + const session = getActiveSession(); + if (!session) return; + session.messages = messageHistory.slice(); + session.updatedAt = Date.now(); + } + + function updateSessionTitle(session) { + if (!session) return; + if (session.title && session.title !== '新会话') return; + const firstUser = session.messages.find(m => m.role === 'user'); + if (!firstUser) return; + const text = getMessageDisplay(firstUser); + if (!text) return; + const title = text.replace(/\n/g, ' ').trim().slice(0, 20); + if (title) { + session.title = title; + } + } + + function renameSession(id, newTitle) { + const session = sessionsData.sessions.find(s => s.id === id); + if (!session) return; + const trimmed = (newTitle || '').trim(); + session.title = trimmed || '新会话'; + session.updatedAt = Date.now(); + saveSessions(); + renderSessionList(); + } + + function startRenameSession(sessionId, titleSpan) { + const session = sessionsData.sessions.find(s => s.id === sessionId); + if (!session) return; + const input = document.createElement('input'); + input.type = 'text'; + input.className = 'session-rename-input'; + input.value = session.title || ''; + input.maxLength = 40; + titleSpan.replaceWith(input); + input.focus(); + input.select(); + const commit = () => { + renameSession(sessionId, input.value); + }; + input.addEventListener('blur', commit); + input.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { e.preventDefault(); input.blur(); } + if (e.key === 'Escape') { input.value = session.title || '新会话'; input.blur(); } + }); + } + + function syncSessionModel() { + const session = getActiveSession(); + if (!session) return; + session.model = modelValue || ''; + } + + function restoreSessionModel() { + const session = getActiveSession(); + if (!session || !session.model) return; + if (modelList.includes(session.model)) { + selectModel(session.model); + } + } + + function renderSessionList() { + if (!sessionListEl || !sessionsData) return; + sessionListEl.innerHTML = ''; + for (const session of sessionsData.sessions) { + const item = document.createElement('div'); + item.className = 'session-item' + (session.id === sessionsData.activeId ? ' active' : ''); + item.dataset.id = session.id; + + const titleSpan = document.createElement('span'); + titleSpan.className = 'session-title'; + titleSpan.textContent = session.title || '新会话'; + titleSpan.addEventListener('dblclick', (e) => { + e.stopPropagation(); + startRenameSession(session.id, titleSpan); + }); + item.appendChild(titleSpan); + + if (session.unread && session.id !== sessionsData.activeId) { + const dot = document.createElement('span'); + dot.className = 'session-unread'; + item.appendChild(dot); + } + + const delBtn = document.createElement('button'); + delBtn.className = 'session-delete'; + delBtn.type = 'button'; + delBtn.title = '删除'; + delBtn.textContent = '×'; + delBtn.addEventListener('click', (e) => { + e.stopPropagation(); + deleteSession(session.id); + }); + item.appendChild(delBtn); + + item.addEventListener('click', () => switchSession(session.id)); + sessionListEl.appendChild(item); + } + } + + function isMobileSidebar() { + return window.matchMedia('(max-width: 1024px)').matches; + } + + function setSidebarCollapsed(collapsed) { + const layout = chatSidebar ? chatSidebar.closest('.chat-layout') : null; + if (!layout) return; + layout.classList.toggle('collapsed', collapsed); + try { + localStorage.setItem(SIDEBAR_STATE_KEY, collapsed ? '1' : '0'); + } catch (e) { + // ignore storage failures + } + } + + function openSidebar() { + if (isMobileSidebar()) { + if (chatSidebar) chatSidebar.classList.add('open'); + if (sidebarOverlay) sidebarOverlay.classList.add('open'); + return; + } + setSidebarCollapsed(false); + } + + function closeSidebar() { + if (isMobileSidebar()) { + if (chatSidebar) chatSidebar.classList.remove('open'); + if (sidebarOverlay) sidebarOverlay.classList.remove('open'); + return; + } + setSidebarCollapsed(true); + } + + function toggleSidebar() { + if (isMobileSidebar()) { + if (chatSidebar && chatSidebar.classList.contains('open')) { + closeSidebar(); + } else { + openSidebar(); + } + return; + } + const layout = chatSidebar ? chatSidebar.closest('.chat-layout') : null; + if (!layout) return; + setSidebarCollapsed(!layout.classList.contains('collapsed')); + } function toast(message, type) { if (typeof showToast === 'function') { @@ -71,6 +440,12 @@ if (emptyState) emptyState.classList.remove('hidden'); } + function setRenderedHTML(el, html) { + // html is pre-sanitized through renderMarkdown → escapeHtml pipeline; + // all user text is entity-escaped before any HTML construction. + el.innerHTML = html; + } + function escapeHtml(value) { return value .replace(/&/g, '&') @@ -80,6 +455,18 @@ .replace(/'/g, '''); } + function isSafeLinkUrl(url) { + const val = String(url || '').trim().toLowerCase(); + if (!val) return false; + return /^(https?:|mailto:|tel:|\/(?!\/)|\.\.?\/|#)/.test(val); + } + + function isSafeImageUrl(url) { + const val = String(url || '').trim().toLowerCase(); + if (!val) return false; + return /^(https?:|data:image\/(?:png|jpe?g|gif|webp|bmp|ico);base64,|\/(?!\/)|\.\.?\/)/.test(val); + } + function renderBasicMarkdown(rawText) { const text = (rawText || '').replace(/\\n/g, '\n'); const escaped = escapeHtml(text); @@ -93,34 +480,49 @@ }); const renderInline = (value) => { - let output = value - .replace(/`([^`]+)`/g, '$1') + const inlineCodes = []; + let output = value.replace(/`([^`]+)`/g, (match, code) => { + const token = `@@INLINE_${inlineCodes.length}@@`; + inlineCodes.push(`${code}`); + return token; + }); + + output = output .replace(/\*\*([^*]+)\*\*/g, '$1') - .replace(/\*([^*]+)\*/g, '$1'); + .replace(/\*([^*]+)\*/g, '$1') + .replace(/~~([^~]+)~~/g, '$1'); output = output.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, url) => { const safeAlt = escapeHtml(alt || 'image'); + if (!isSafeImageUrl(url)) return safeAlt; const safeUrl = escapeHtml(url || ''); return `${safeAlt}`; }); output = output.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, label, url) => { const safeLabel = escapeHtml(label || ''); + if (!isSafeLinkUrl(url)) return safeLabel; const safeUrl = escapeHtml(url || ''); return `${safeLabel}`; }); output = output.replace(/(data:image\/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=]+)/g, (match, uri) => { + if (!isSafeImageUrl(uri)) return ''; const safeUrl = escapeHtml(uri || ''); return `image`; }); + inlineCodes.forEach((html, i) => { + output = output.replace(new RegExp(`@@INLINE_${i}@@`, 'g'), html); + }); + return output; }; const lines = fenced.split(/\r?\n/); const htmlParts = []; let inUl = false; + let inUlTask = false; let inOl = false; let inTable = false; let paragraphLines = []; @@ -129,6 +531,7 @@ if (inUl) { htmlParts.push(''); inUl = false; + inUlTask = false; } if (inOl) { htmlParts.push(''); @@ -186,6 +589,31 @@ continue; } + if (/^(-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { + flushParagraph(); + closeLists(); + closeTable(); + htmlParts.push('
'); + continue; + } + + if (/^\s*>/.test(line)) { + flushParagraph(); + closeLists(); + closeTable(); + const quoteLines = []; + let j = i; + for (; j < lines.length; j += 1) { + const currentLine = lines[j]; + if (!/^\s*>/.test(currentLine)) break; + quoteLines.push(currentLine.replace(/^\s*>\s?/, '')); + } + i = j - 1; + const quoteText = quoteLines.join('\n'); + htmlParts.push(`
${renderBasicMarkdown(quoteText)}
`); + continue; + } + if (trimmed.includes('|')) { const nextLine = lines[i + 1] || ''; if (!inTable && isTableSeparator(nextLine.trim())) { @@ -208,6 +636,24 @@ } } + const taskMatch = trimmed.match(/^[-*+•·]\s+\[([ xX])\]\s+(.*)$/); + if (taskMatch) { + flushParagraph(); + if (inUl && !inUlTask) { + closeLists(); + } + if (!inUl) { + closeLists(); + closeTable(); + htmlParts.push('