From ec4d5102d2c4dfdce38243e5ae43d2777d2916f2 Mon Sep 17 00:00:00 2001 From: zhiqui Date: Sat, 14 Nov 2026 23:35:13 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B9=E5=AF=86=E7=A0=81=3D=E6=97=A7?= =?UTF-8?q?=E5=AF=86=E9=92=A5=E8=A7=A3=E5=AF=86=E2=86=92=E6=96=B0=E5=AF=86?= =?UTF-8?q?=E9=92=A5=E9=87=8D=E5=8A=A0=E5=AF=86(=E5=90=AB=E6=98=8E?= =?UTF-8?q?=E6=96=87=E8=BF=81=E7=A7=BB=E6=95=B0=E6=8D=AE)=EF=BC=9B?= =?UTF-8?q?=E8=A7=92=E8=89=B2=E4=BA=BA=E8=AE=BE/=E5=BC=80=E5=9C=BA?= =?UTF-8?q?=E7=99=BD=E7=BA=B3=E5=85=A5=E5=8A=A0=E5=AF=86=E8=8C=83=E5=9B=B4?= =?UTF-8?q?=EF=BC=9B=E5=90=8E=E5=8F=B0=E6=B8=A0=E9=81=93=E5=88=86=E9=85=8D?= =?UTF-8?q?UI+=E6=94=B9=E5=AF=86=E7=A0=81=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/routers/auth.py | 46 ++++++++++++++++++++++++++++++++ app/api/routers/characters.py | 17 ++++++++++-- app/api/routers/chat.py | 8 +++--- web/index.html | 1 + web/js/app.js | 50 ++++++++++++++++++++++++++++++++++- 5 files changed, 116 insertions(+), 6 deletions(-) diff --git a/app/api/routers/auth.py b/app/api/routers/auth.py index b4e58ef1..61fed888 100644 --- a/app/api/routers/auth.py +++ b/app/api/routers/auth.py @@ -109,3 +109,49 @@ async def delete_account(body: AuthIn, user: User = Depends(current_user), db=De @router.get("/me") async def me(user: User = Depends(current_user)): return {"id": user.id, "username": user.username, "is_admin": user.is_admin} + + +class ChangePasswordIn(BaseModel): + old_password: str + new_password: str + + +@router.post("/change_password") +async def change_password(body: ChangePasswordIn, user: User = Depends(current_user), + db=Depends(get_db)): + """旧密码解密 → 新密码重加密 → 换盐换 hash。""" + if not security.verify_password(body.old_password, user.password_hash): + raise HTTPException(401, "旧密码错误") + if len(body.new_password) < 6: + raise HTTPException(400, "新密码至少6位") + old_key = security.derive_key(body.old_password, bytes.fromhex(user.kdf_salt)) + new_salt = security.os.urandom(16) + new_key = security.derive_key(body.new_password, new_salt) + + # 当前是否要求加密落库 + from ...db import repos as _repos + need_encrypt = await _repos.SettingRepo.get(db, "admin_data_visible") != "true" + + from ...models.entities import (Memory, WorldbookEntry, Character, + ChatSession, Message) + tables = [(Memory, "content_enc"), (WorldbookEntry, "content_enc"), + (Message, "content_enc"), (ChatSession, "novel_setting_enc"), + (Character, "persona"), (Character, "greeting")] + for model, col in tables: + rows = (await db.execute( + select(model).where(model.user_id == user.id))).scalars().all() + for row in rows: + v = getattr(row, col) + if not v: + continue + plain = (security.decrypt_text(old_key, v) + if security.is_encrypted(v) else v) + setattr(row, col, security.encrypt_text(new_key, plain) + if need_encrypt else plain) + + user.kdf_salt = new_salt.hex() + user.password_hash = security.hash_password(body.new_password) + await db.commit() + security.key_cache[user.id] = new_key + return {"ok": True} + diff --git a/app/api/routers/characters.py b/app/api/routers/characters.py index 925f2b85..f364c0ff 100644 --- a/app/api/routers/characters.py +++ b/app/api/routers/characters.py @@ -50,16 +50,28 @@ async def _own_character(db, user, cid) -> Character: @router.get("") async def list_characters(user: User = Depends(current_user), db=Depends(get_db)): rows = await repos.CharacterRepo.list_for(db, user.id) - return {"characters": [{"id": c.id, "name": c.name, "persona": c.persona, - "greeting": c.greeting, "voice": c.voice, + key = _key(user) + return {"characters": [{"id": c.id, "name": c.name, "persona": repos.dec(key, c.persona), + "greeting": repos.dec(key, c.greeting), "voice": c.voice, "avatar_url": c.avatar_url, "source": c.source, "novel_id": c.novel_id} for c in rows]} +async def _enc_persona(user, c): + """人设/开场白按当前开关决定是否加密落库""" + db = c._sa_instance_state.session + key = _key(user) + visible = await repos.SettingRepo.get(db, "admin_data_visible") == "true" + ek = None if visible else key + c.persona = repos.enc(ek, c.persona) + c.greeting = repos.enc(ek, c.greeting) + + @router.post("") async def create_character(body: CharacterIn, user: User = Depends(current_user), db=Depends(get_db)): c = Character(user_id=user.id, **body.model_dump()) + await _enc_persona(user, c) db.add(c) await db.commit() return {"id": c.id} @@ -71,6 +83,7 @@ async def update_character(cid: int, body: CharacterIn, c = await _own_character(db, user, cid) for k, v in body.model_dump().items(): setattr(c, k, v) + await _enc_persona(user, c) await db.commit() return {"ok": True} diff --git a/app/api/routers/chat.py b/app/api/routers/chat.py index cd1e0b52..6e72b602 100644 --- a/app/api/routers/chat.py +++ b/app/api/routers/chat.py @@ -11,6 +11,7 @@ from ...db import repos from ...models.entities import (User, ChatSession, Message, Character, Memory, WorldbookEntry) from ...api.routers.auth import current_user +from ...api.routers.characters import _enc_persona, _key # noqa from ...core import security from ...services.llm import LLMClient from ...services import novel_pipeline @@ -74,7 +75,7 @@ async def build_context(db, user, session, history) -> list[dict]: msgs = [] if session.mode == "roleplay": ch = await db.get(Character, session.character_id) - persona = f"你扮演角色「{ch.name}」。人设:\n{ch.persona}\n始终以该角色的口吻回复,不要出戏。" + persona = f"你扮演角色「{ch.name}」。人设:\n{_dec(user, ch.persona)}\n始终以该角色的口吻回复,不要出戏。" mems = await repos.MemoryRepo.list_for(db, user.id, ch.id) key = _key(user) mem_text = "\n".join(f"- [{m.kind}] {_dec(user, m.content_enc)}" for m in mems) @@ -125,7 +126,7 @@ async def create_session(body: SessionIn, user: User = Depends(current_user), ch = await db.get(Character, body.character_id) if ch and ch.greeting: db.add(Message(session_id=s.id, user_id=user.id, role="assistant", - speaker=ch.name, content_enc=_enc(user, ch.greeting))) + speaker=ch.name, content_enc=_enc(user, _dec(user, ch.greeting)))) await db.commit() return {"id": s.id} @@ -190,6 +191,7 @@ async def _run_extraction(db, user, session, client, models, auto_avatar, story_ data["avatar_url"] = await novel_pipeline.gen_avatar( client, image_model, d.get("appearance", "")) ch = Character(**data) + await _enc_persona(user, ch) db.add(ch) await db.flush() # 自动记忆 @@ -205,7 +207,7 @@ async def _run_extraction(db, user, session, client, models, auto_avatar, story_ content_enc=repos.enc(None if visible else key, f"{d['name']}:{d.get('identity','')}。" f"{d.get('personality','')} 与主角关系:{d.get('relation','')}"))) - out.append({"id": ch.id, "name": ch.name, "persona": ch.persona, + out.append({"id": ch.id, "name": ch.name, "persona": _dec(user, ch.persona), "avatar_url": ch.avatar_url, "voice": ch.voice}) await db.commit() return out diff --git a/web/index.html b/web/index.html index 4c148fed..828eb836 100644 --- a/web/index.html +++ b/web/index.html @@ -32,6 +32,7 @@ + diff --git a/web/js/app.js b/web/js/app.js index b8aea387..7ea8201c 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -350,7 +350,7 @@ async function loadAdmin() { `).join(""); const u = await api("/admin/users"); $("#admin-stats").textContent = `用户 ${u.stats.users} · 会话 ${u.stats.sessions}`; - $("#admin-users").innerHTML = u.users.map(x => + $("#admin-users").innerHTML = `` + u.users.map(x => `
${esc(x.username)} ${x.is_admin ? '管理员' : ""} ${x.is_active ? "" : '已封禁'}
@@ -399,6 +399,54 @@ async function guideNext() { loadChannels(); } +/* ---------- 改密码(自动重加密) ---------- */ +function editPassword() { + openModal(`

修改密码

+

加密数据将自动用旧密码解密、新密码重加密,历史记录无损。

+ + +
+ +
`); +} +async function savePassword() { + try { + await api("/auth/change_password", { method: "POST", body: { + old_password: $("#pw-old").value, new_password: $("#pw-new").value } }); + closeModal(); toast("密码已修改,加密数据已重加密"); + } catch (e) { toast(e.message); } +} + +/* ---------- 后台:渠道分配 ---------- */ +async function adminGrantChannel() { + const chans = (await api("/channels")).channels; // 管理员可见全部 + const users = (await api("/admin/users")).users; + openModal(`

渠道分配

+ + +
+ +
+
`); + const c = +$("#gr-chan").value; + const g = await api(`/channels/${c}/grants`); + $("#gr-list").innerHTML = g.user_ids.length + ? "已授权用户: " + g.user_ids.map(uid => { + const u = users.find(x => x.id === uid); + return `${esc(u ? u.username : uid)} + `; + }).join(" ") + : '

该渠道尚未授权给任何用户。

'; +} +async function doGrant() { + await api(`/admin/channels/${$("#gr-chan").value}/grant/${$("#gr-user").value}`, { method: "POST" }); + adminGrantChannel(); toast("已授权"); +} +async function revokeGrant(cid, uid) { + await api(`/admin/channels/${cid}/grant/${uid}`, { method: "DELETE" }); + adminGrantChannel(); +} + /* ---------- 通用 ---------- */ function openModal(html) { $("#modal").innerHTML = html; $("#modal").classList.remove("hidden"); $("#modal-mask").classList.remove("hidden"); }