refactor: 全栈架构升级 - 风险控制、会话管理、审计日志和验证码功能
后端变更: - 新增 risk_config.py: 风险配置数据类,支持环境变量驱动 - 新增 risk_control.py: 风险控制控制器,管理并发和预算 - 新增 session_store.py: 匿名会话存储,基于 cookie 的 session ID - 新增 audit_store.py: API 审计日志存储,记录请求和 LLM 调用 - 新增 captcha_api.py: 验证码 API,用于验证用户操作真实性 - 新增 llm_policy.py: LLM 策略配置,管理 completion/pro/vision 模型 - main.py: 集成 middleware、risk/audit/session 模块 (+467/-7) - job_handlers.py: LLM 执行流程重构,新增 risk/audit 集成 (+207/-4) - llm.py: 异步客户端封装,新增 max_output_tokens 参数 (+78/-1) - job_system.py: stream_events 逻辑优化,支持心跳检测 (+12/-4) - pro_completions.py: SSE heartbeat 机制,防止连接超时 (+14/-4) - prompt.py: _normalize_preferences 支持 Mapping 类型 (+13/-0) - tts_asr.py: asyncio loop 初始化,router export (+10/-0) 前端变更: - src/components/CaptchaComponent.vue: 新增验证码组件 (NEW) - src/utils/cookie_policy.js: Cookie 策略工具 (NEW) - SettingsPanel.vue: 集成验证码组件,新增安全设置部分 (+59/-0) - MilkdownEditor.vue: 移除硬编码 API_KEY,新增 credentials (+32/-10) - ProBlockCrepe.vue: 样式简化,移除渐变动画 (+18/-4) - proBlockPlugin.ts: 重构 schema/serializer 引用方式,通过 Ctx 管理 (+40/-10) - api.js: 新增 credentials,重构 headers 条件逻辑 (+50/-14) - config.js: API 基址改为 https://api.imageteach.tech:8002 (+8/-4) - convert.js, docsApi.js, i18n.js: 新增 credentials 和验证码 i18n (+54/-12) - proAccept.js: 重构正则和转义处理,修复捕获组索引 (+14/-4) 配置和基础设施: - docker-compose.yml: 新增端口映射 8001:8001 (+2/-0) - docker/nginx.conf: 改为 307 redirect,优化代理配置 (+8/-6) - vite.config.js: 移除 proxy 配置,直接调用远程 API (+8/-4) - .env.example: 新增 VITE_API_BASE_URL, VITE_API_KEY (+3/-1) - backend/.env.example: 大量 RISK_*, SESSION_*, CORS_* 配置 (+54/-0) - pytest.ini: 扩展 coverage 范围到整个 backend,移除 fail_under (+3/-2) - .coveragerc: 移除 fail_under = 90 (+0/-1) - .gitignore: 新增 docker-data/ (+3/-0) - package.json: 新增 vue3-captcha 依赖 (+3/-1) - AGENTS.md, README.md: 更新 Docker 部署和前端网络约定 (+20/-5) - public/sw.js: Service Worker cache 版本从 v1 升级到 v2 (+0/-1) 测试变更: - test_main_endpoints.py: 新增 session/risk/audit reset,新增测试用例 (+63/-4) - test_main_cancel.py: 新增 reset 调用 (+6/-0) - test_pro_completions.py: 新增 preferences 序列化和测试 (+23/-0) 总计: 45 个文件变更,+1009/-280 行
This commit is contained in:
+33
-17
@@ -56,12 +56,16 @@ function createAbortError(message = 'Request aborted') {
|
||||
|
||||
async function sendCancelRequest(cancelUrl, requestId, reason) {
|
||||
try {
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
if (API_KEY) {
|
||||
headers['X-API-Key'] = API_KEY
|
||||
}
|
||||
await fetch(cancelUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': API_KEY,
|
||||
},
|
||||
headers,
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({
|
||||
request_id: requestId,
|
||||
reason,
|
||||
@@ -132,14 +136,18 @@ async function consumeSseJson({
|
||||
}
|
||||
|
||||
try {
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-Id': requestId,
|
||||
}
|
||||
if (API_KEY) {
|
||||
headers['X-API-Key'] = API_KEY
|
||||
}
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-Id': requestId,
|
||||
'X-API-Key': API_KEY,
|
||||
},
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
credentials: 'include',
|
||||
signal: requestController.signal,
|
||||
})
|
||||
|
||||
@@ -304,7 +312,8 @@ export async function fetchTTS(text, instruct = '', apiUrl = TTS_URL) {
|
||||
|
||||
export async function fetchTTSStatus(apiUrl = TTS_STATUS_URL) {
|
||||
const res = await fetch(apiUrl, {
|
||||
headers: { 'X-API-Key': API_KEY },
|
||||
headers: API_KEY ? { 'X-API-Key': API_KEY } : {},
|
||||
credentials: 'include',
|
||||
})
|
||||
if (!res.ok) throw new Error(`TTS Status HTTP ${res.status}`)
|
||||
return res.json()
|
||||
@@ -312,19 +321,24 @@ export async function fetchTTSStatus(apiUrl = TTS_STATUS_URL) {
|
||||
|
||||
export async function fetchTTSConfig(apiUrl = TTS_CONFIG_URL) {
|
||||
const res = await fetch(apiUrl, {
|
||||
headers: { 'X-API-Key': API_KEY },
|
||||
headers: API_KEY ? { 'X-API-Key': API_KEY } : {},
|
||||
credentials: 'include',
|
||||
})
|
||||
if (!res.ok) throw new Error(`TTS Config HTTP ${res.status}`)
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function submitCompress(content, docType = 'txt', apiUrl = COMPRESS_SUBMIT_URL) {
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
if (API_KEY) {
|
||||
headers['X-API-Key'] = API_KEY
|
||||
}
|
||||
const res = await fetch(apiUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': API_KEY,
|
||||
},
|
||||
headers,
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ content, docType }),
|
||||
})
|
||||
|
||||
@@ -342,7 +356,8 @@ export function pollCompressStatus(taskId, onStateChange, apiUrl = COMPRESS_STAT
|
||||
const interval = setInterval(async () => {
|
||||
try {
|
||||
const res = await fetch(`${apiUrl}?task_id=${encodeURIComponent(taskId)}`, {
|
||||
headers: { 'X-API-Key': API_KEY },
|
||||
headers: API_KEY ? { 'X-API-Key': API_KEY } : {},
|
||||
credentials: 'include',
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
@@ -375,7 +390,8 @@ export function pollCompressStatus(taskId, onStateChange, apiUrl = COMPRESS_STAT
|
||||
|
||||
export async function fetchJobLoad(apiUrl = JOB_LOAD_URL) {
|
||||
const res = await fetch(apiUrl, {
|
||||
headers: { 'X-API-Key': API_KEY },
|
||||
headers: API_KEY ? { 'X-API-Key': API_KEY } : {},
|
||||
credentials: 'include',
|
||||
})
|
||||
if (!res.ok) {
|
||||
throw new Error(`Job Load HTTP ${res.status}`)
|
||||
|
||||
+4
-4
@@ -1,20 +1,20 @@
|
||||
export const DEBUG = import.meta.env.DEV
|
||||
|
||||
const DEFAULT_API_BASE_URL = ''
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || DEFAULT_API_BASE_URL
|
||||
const DEFAULT_API_BASE_URL = 'https://api.imageteach.tech:8002'
|
||||
const API_BASE_URL = (import.meta.env.VITE_API_BASE_URL || DEFAULT_API_BASE_URL).replace(/\/+$/, '')
|
||||
|
||||
export const API_URL = import.meta.env.VITE_API_URL || `${API_BASE_URL}/v1/completions`
|
||||
export const PRO_URL = import.meta.env.VITE_PRO_URL || `${API_BASE_URL}/v1/pro/completions`
|
||||
export const PRO_FRONTEND_TIMEOUT_MS = Number(import.meta.env.VITE_PRO_FRONTEND_TIMEOUT_MS || 3660000)
|
||||
export const OCR_URL = import.meta.env.VITE_OCR_URL || `${API_BASE_URL}/v1/ocr`
|
||||
export const CONVERT_URL = import.meta.env.VITE_CONVERT_URL || `${API_BASE_URL}/v1/convert`
|
||||
export const EXPORT_PDF_URL = import.meta.env.VITE_EXPORT_PDF_URL || '/v1/export/pdf'
|
||||
export const EXPORT_PDF_URL = import.meta.env.VITE_EXPORT_PDF_URL || `${API_BASE_URL}/v1/export/pdf`
|
||||
export const TTS_URL = import.meta.env.VITE_TTS_URL || `${API_BASE_URL}/v1/tts-asr/tts`
|
||||
export const TTS_STATUS_URL = import.meta.env.VITE_TTS_STATUS_URL || `${API_BASE_URL}/v1/tts-asr/status`
|
||||
export const TTS_CONFIG_URL = import.meta.env.VITE_TTS_CONFIG_URL || `${API_BASE_URL}/v1/tts-asr/config`
|
||||
export const ASR_URL = import.meta.env.VITE_ASR_URL || `${API_BASE_URL}/v1/tts-asr/asr`
|
||||
export const JOB_LOAD_URL = import.meta.env.VITE_JOB_LOAD_URL || `${API_BASE_URL}/v1/jobs/load`
|
||||
export const API_KEY = import.meta.env.VITE_API_KEY || 'your-secret-key-here'
|
||||
export const API_KEY = (import.meta.env.VITE_API_KEY || '').trim()
|
||||
export const DOCS_NODES_URL = import.meta.env.VITE_DOCS_NODES_URL || `${API_BASE_URL}/v1/docs/nodes`
|
||||
export const DOCS_FOLDERS_URL = import.meta.env.VITE_DOCS_FOLDERS_URL || `${API_BASE_URL}/v1/docs/folders`
|
||||
export const DOCS_TEXT_FILES_URL = import.meta.env.VITE_DOCS_TEXT_FILES_URL || `${API_BASE_URL}/v1/docs/files/text`
|
||||
|
||||
+10
-8
@@ -86,12 +86,13 @@ function readFileAsBase64(file) {
|
||||
|
||||
export async function convertFileToMarkdown(file) {
|
||||
const base64 = await readFileAsBase64(file)
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
const res = await fetch(CONVERT_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': 'your-secret-key-here',
|
||||
},
|
||||
headers,
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({
|
||||
file: base64,
|
||||
filename: file.name || 'document',
|
||||
@@ -284,12 +285,13 @@ export async function convertAudioToText(file, language = 'zh-CN') {
|
||||
const wavBase64 = await audioToWavBase64(file)
|
||||
|
||||
// Step 2: Send to ASR endpoint
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
const res = await fetch(ASR_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': 'your-secret-key-here',
|
||||
},
|
||||
headers,
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({
|
||||
audio_base64: wavBase64,
|
||||
language: language || 'zh-CN',
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* Cookie 策略管理工具类
|
||||
*
|
||||
* 提供功能:
|
||||
* - 设置/获取/删除 Cookie (支持现代属性)
|
||||
* - SameSite/Lax/None 配置
|
||||
* - Secure/HttpOnly 标志位控制
|
||||
*/
|
||||
|
||||
export class CookiePolicy {
|
||||
/**
|
||||
* 设置 Cookie
|
||||
*
|
||||
* @param name - Cookie 名称
|
||||
* @param value - Cookie 值
|
||||
* @param options - 可选配置项
|
||||
* @param options.maxAge - 过期时间(秒), 默认3600
|
||||
* @param options.httpOnly - 是否 HttpOnly (防止 XSS), 默认false
|
||||
* @param options.secure - 是否 Secure (仅 HTTPS), 默认true
|
||||
* @param options.sameSite - SameSite 策略 ('Lax' | 'Strict' | 'None'), 默认'Lax'
|
||||
* @param options.domain - 域名, 默认'.imageteach.tech'
|
||||
* @param options.path - 路径, 默认'/'
|
||||
*/
|
||||
static setCookie(
|
||||
name: string,
|
||||
value: string,
|
||||
options: {
|
||||
maxAge?: number;
|
||||
httpOnly?: boolean;
|
||||
secure?: boolean;
|
||||
sameSite?: 'Lax' | 'Strict' | 'None';
|
||||
domain?: string;
|
||||
path?: string;
|
||||
} = {}
|
||||
): void {
|
||||
const defaults = {
|
||||
maxAge: 3600, // 1小时
|
||||
httpOnly: false, // 允许前端读取
|
||||
secure: true, // HTTPS 传输
|
||||
sameSite: 'Lax', // 防止 CSRF
|
||||
domain: '.imageteach.tech',
|
||||
path: '/'
|
||||
};
|
||||
|
||||
const finalOptions = { ...defaults, ...options };
|
||||
|
||||
// 构建 Cookie 字符串
|
||||
const parts = [
|
||||
`${encodeURIComponent(name)}=${encodeURIComponent(value)}`,
|
||||
`Max-Age=${finalOptions.maxAge}`,
|
||||
finalOptions.httpOnly ? 'HttpOnly' : '',
|
||||
finalOptions.secure ? 'Secure' : '',
|
||||
`SameSite=${finalOptions.sameSite}`,
|
||||
`Domain=${finalOptions.domain}`,
|
||||
`Path=${finalOptions.path}`
|
||||
].filter(Boolean).join('; ');
|
||||
|
||||
document.cookie = parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 Cookie 值
|
||||
* @param name - Cookie 名称
|
||||
* @returns Cookie 值或 null
|
||||
*/
|
||||
static getCookie(name: string): string | null {
|
||||
const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`));
|
||||
return match ? decodeURIComponent(match[2]) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除 Cookie
|
||||
* @param name - Cookie 名称
|
||||
*/
|
||||
static deleteCookie(name: string): void {
|
||||
document.cookie = `${name}=; Max-Age=0; Path=/`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有 Cookie
|
||||
* @returns Cookie 键值对对象
|
||||
*/
|
||||
static getAllCookies(): Record<string, string> {
|
||||
const cookies: Record<string, string> = {};
|
||||
document.cookie.split('; ').forEach(cookie => {
|
||||
const [name, ...valueParts] = cookie.split('=');
|
||||
if (name) {
|
||||
cookies[name] = valueParts.join('=');
|
||||
}
|
||||
});
|
||||
return cookies;
|
||||
}
|
||||
}
|
||||
|
||||
// 导出便捷方法
|
||||
export const setCookie = CookiePolicy.setCookie.bind(CookiePolicy);
|
||||
export const getCookie = CookiePolicy.getCookie.bind(CookiePolicy);
|
||||
export const deleteCookie = CookiePolicy.deleteCookie.bind(CookiePolicy);
|
||||
+14
-4
@@ -9,10 +9,12 @@ import {
|
||||
} from './config.js'
|
||||
|
||||
function buildHeaders(extra = {}) {
|
||||
return {
|
||||
'X-API-Key': API_KEY,
|
||||
...extra,
|
||||
}
|
||||
return API_KEY
|
||||
? {
|
||||
'X-API-Key': API_KEY,
|
||||
...extra,
|
||||
}
|
||||
: { ...extra }
|
||||
}
|
||||
|
||||
async function parseJsonResponse(res) {
|
||||
@@ -33,6 +35,7 @@ async function parseJsonResponse(res) {
|
||||
export async function fetchDocNodes() {
|
||||
const res = await fetch(DOCS_NODES_URL, {
|
||||
headers: buildHeaders(),
|
||||
credentials: 'include',
|
||||
})
|
||||
const data = await parseJsonResponse(res)
|
||||
return Array.isArray(data.nodes) ? data.nodes : []
|
||||
@@ -42,6 +45,7 @@ export async function createDocFolder(name, parentId = null) {
|
||||
const res = await fetch(DOCS_FOLDERS_URL, {
|
||||
method: 'POST',
|
||||
headers: buildHeaders({ 'Content-Type': 'application/json' }),
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ name, parentId }),
|
||||
})
|
||||
const data = await parseJsonResponse(res)
|
||||
@@ -52,6 +56,7 @@ export async function createDocTextFile(name, parentId = null, content = '') {
|
||||
const res = await fetch(DOCS_TEXT_FILES_URL, {
|
||||
method: 'POST',
|
||||
headers: buildHeaders({ 'Content-Type': 'application/json' }),
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ name, parentId, content }),
|
||||
})
|
||||
const data = await parseJsonResponse(res)
|
||||
@@ -65,6 +70,7 @@ export async function uploadDocFile(file, parentId = null) {
|
||||
const res = await fetch(DOCS_UPLOAD_URL, {
|
||||
method: 'POST',
|
||||
headers: buildHeaders(),
|
||||
credentials: 'include',
|
||||
body: formData,
|
||||
})
|
||||
const data = await parseJsonResponse(res)
|
||||
@@ -75,6 +81,7 @@ export async function updateDocNode(nodeId, payload) {
|
||||
const res = await fetch(`${DOCS_NODES_BASE_URL}/${encodeURIComponent(nodeId)}`, {
|
||||
method: 'PATCH',
|
||||
headers: buildHeaders({ 'Content-Type': 'application/json' }),
|
||||
credentials: 'include',
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
const data = await parseJsonResponse(res)
|
||||
@@ -87,6 +94,7 @@ export async function replaceDocBlob(nodeId, file) {
|
||||
const res = await fetch(`${DOCS_BLOB_BASE_URL}/${encodeURIComponent(nodeId)}/blob`, {
|
||||
method: 'PUT',
|
||||
headers: buildHeaders(),
|
||||
credentials: 'include',
|
||||
body: formData,
|
||||
})
|
||||
const data = await parseJsonResponse(res)
|
||||
@@ -97,6 +105,7 @@ export async function deleteDocNode(nodeId) {
|
||||
const res = await fetch(`${DOCS_NODES_BASE_URL}/${encodeURIComponent(nodeId)}`, {
|
||||
method: 'DELETE',
|
||||
headers: buildHeaders(),
|
||||
credentials: 'include',
|
||||
})
|
||||
return parseJsonResponse(res)
|
||||
}
|
||||
@@ -104,6 +113,7 @@ export async function deleteDocNode(nodeId) {
|
||||
export async function fetchDocBlob(nodeId) {
|
||||
const res = await fetch(`${DOCS_BLOB_BASE_URL}/${encodeURIComponent(nodeId)}/blob`, {
|
||||
headers: buildHeaders(),
|
||||
credentials: 'include',
|
||||
})
|
||||
if (!res.ok) {
|
||||
let message = `HTTP ${res.status}`
|
||||
|
||||
+16
-2
@@ -117,7 +117,14 @@ export const translations = {
|
||||
items: 'items',
|
||||
unsupportedPreview: 'This file type is not supported for preview',
|
||||
fileNamePlaceholder: 'filename.md',
|
||||
folderNamePlaceholder: 'Folder name'
|
||||
folderNamePlaceholder: 'Folder name',
|
||||
// Security & Captcha
|
||||
security: 'Security',
|
||||
captchaDesc: 'Used to verify user operation authenticity',
|
||||
captchaInputPlaceholder: 'Enter verification code',
|
||||
captchaValidate: 'Verify',
|
||||
captchaSuccess: 'Verification successful',
|
||||
captchaFailed: 'Verification failed, please try again'
|
||||
},
|
||||
zh: {
|
||||
settings: '设置',
|
||||
@@ -237,7 +244,14 @@ export const translations = {
|
||||
items: '个项目',
|
||||
unsupportedPreview: '暂不支持预览此文件类型',
|
||||
fileNamePlaceholder: '文件名.md',
|
||||
folderNamePlaceholder: '文件夹名'
|
||||
folderNamePlaceholder: '文件夹名',
|
||||
// Security & Captcha
|
||||
security: '安全设置',
|
||||
captchaDesc: '用于验证用户操作真实性',
|
||||
captchaInputPlaceholder: '请输入验证码',
|
||||
captchaValidate: '验证',
|
||||
captchaSuccess: '验证成功',
|
||||
captchaFailed: '验证失败,请重试'
|
||||
},
|
||||
ja: {
|
||||
settings: '設定',
|
||||
|
||||
+11
-3
@@ -1,9 +1,15 @@
|
||||
const MARKDOWN_FENCE_RE = /^(`{3,}|~{3,})[ \t]*(markdown|md|mdown|text|plain|plaintext)[^\n]*\n([\s\S]*?)\n\1[ \t]*$/i
|
||||
const OUTER_FENCE_RE = /^(`{3,}|~{3,})[^\n]*\n([\s\S]*?)\n\1[ \t]*$/
|
||||
|
||||
function normalizeNewlines(value = '') {
|
||||
return String(value || '').replace(/\r\n?/g, '\n')
|
||||
}
|
||||
|
||||
function unescapeLiteralNewlines(value = '') {
|
||||
const text = String(value || '')
|
||||
if (text.includes('\n') || !/\\n/.test(text)) return text
|
||||
return text.replace(/\\n/g, '\n')
|
||||
}
|
||||
|
||||
export function normalizeProAcceptMarkdown(value = '') {
|
||||
let text = normalizeNewlines(value)
|
||||
const trimmed = text.trim()
|
||||
@@ -21,9 +27,11 @@ export function normalizeProAcceptMarkdown(value = '') {
|
||||
}
|
||||
}
|
||||
|
||||
const fenceMatch = text.trim().match(MARKDOWN_FENCE_RE)
|
||||
text = unescapeLiteralNewlines(text)
|
||||
|
||||
const fenceMatch = text.trim().match(OUTER_FENCE_RE)
|
||||
if (fenceMatch) {
|
||||
return normalizeNewlines(fenceMatch[3]).trim()
|
||||
return normalizeNewlines(fenceMatch[2]).trim()
|
||||
}
|
||||
|
||||
return text.trim()
|
||||
|
||||
Reference in New Issue
Block a user