feat(nsfw): 持久化账号偏好并接入生成控制
- digital.profile.ts: 未保存偏好时默认开启,原子合并 JSON 保留其他资料 - digital.controller.ts、digital.users.ts: 接入本人和管理员偏好读写、事务及审计 - digital.chat.ts、digital.prompt.ts、digital.suggestions.ts: 各生成入口读取服务端账号偏好,保留游客鉴权 - tests/digital-*.test.ts: 覆盖默认值、关闭保留、旧客户端兼容与越权拦截 - README.md: 同步模块职责和发布要求
This commit is contained in:
@@ -18,10 +18,11 @@ type Last = {
|
||||
/** 夹具只替换数据库和上游模型,路由校验、事务、提示词和 SSE 编排执行真实代码。 */
|
||||
async function exercise(
|
||||
t: TestContext,
|
||||
mode: "continue" | "regenerate",
|
||||
mode: "send" | "continue" | "regenerate",
|
||||
last: Last | null,
|
||||
lease = true,
|
||||
previous?: Last,
|
||||
nsfwEnabled?: boolean,
|
||||
) {
|
||||
const original = env.DEEPSEEK_API_KEY;
|
||||
env.DEEPSEEK_API_KEY = "unit-test-no-network";
|
||||
@@ -33,6 +34,10 @@ async function exercise(
|
||||
rolledBack = false;
|
||||
const query = async (q: { sql: string }, args: unknown[]) => {
|
||||
const sql = q.sql;
|
||||
if (sql.startsWith("SELECT body FROM dh_profiles")) {
|
||||
assert.deepEqual(args, ["user:1"]);
|
||||
return [nsfwEnabled === undefined ? [] : [{ body: { nsfwEnabled } }], []];
|
||||
}
|
||||
if (sql.startsWith("SELECT * FROM dh_conversations"))
|
||||
return [
|
||||
[
|
||||
@@ -132,7 +137,13 @@ async function exercise(
|
||||
method: "POST",
|
||||
url: "/api/digital/conversations/continue-unit/stream",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { mode, content: "", requestId: randomUUID() },
|
||||
payload: {
|
||||
mode,
|
||||
content: mode === "send" ? "新的用户台词" : "",
|
||||
requestId: randomUUID(),
|
||||
// 未信任的请求字段不能覆盖服务端账号偏好。
|
||||
nsfwEnabled: nsfwEnabled === false,
|
||||
},
|
||||
});
|
||||
return { response, writes, upstream, rolledBack };
|
||||
} finally {
|
||||
@@ -254,6 +265,31 @@ test("匿名继续请求仍被拒绝", async () => {
|
||||
}
|
||||
});
|
||||
|
||||
for (const mode of ["send", "continue", "regenerate"] as const)
|
||||
for (const nsfwEnabled of [true, false])
|
||||
test(`${mode} 使用账号保存的 NSFW=${nsfwEnabled},忽略请求体的相反值`, async (t) => {
|
||||
const result = await exercise(
|
||||
t,
|
||||
mode,
|
||||
{
|
||||
role: "assistant",
|
||||
content: "已有角色回复",
|
||||
status: "complete",
|
||||
sequence_id: 3,
|
||||
},
|
||||
true,
|
||||
undefined,
|
||||
nsfwEnabled,
|
||||
);
|
||||
assert.match(result.response.body, /event: done/);
|
||||
const system = result.upstream?.find(
|
||||
(message) => message.role === "system",
|
||||
)?.content;
|
||||
assert.ok(system);
|
||||
assert.ok(system.includes(nsfwEnabled ? "NSFW 已开启" : "NSFW 已关闭"));
|
||||
assert.match(system, /禁止涉及未成年人的性内容/);
|
||||
});
|
||||
|
||||
for (const status of ["stopped", "failed"])
|
||||
test(`空${status}记录不阻止接着上段角色内容继续`, async (t) => {
|
||||
const r = await exercise(
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
/** NSFW 账号偏好的默认值、真实路由保存、账号隔离与游客鉴权回归。 */
|
||||
import "./digital-env";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createApp } from "../src/app";
|
||||
import { pool } from "../src/db/pool";
|
||||
import { authService } from "../src/modules/auth/auth.service";
|
||||
import { parseDigitalProfile } from "../src/modules/digital/digital.profile";
|
||||
import {
|
||||
digitalUsers,
|
||||
digitalUserInput,
|
||||
digitalUserUpdate,
|
||||
updateDigitalUser,
|
||||
} from "../src/modules/digital/digital.users";
|
||||
|
||||
test("新账号和旧版资料默认开启,已保存的关闭不被默认值覆盖", () => {
|
||||
for (const body of [
|
||||
undefined,
|
||||
null,
|
||||
{},
|
||||
{ favorites: ["card"], userName: "旧用户" },
|
||||
])
|
||||
assert.equal(parseDigitalProfile(body).nsfwEnabled, true);
|
||||
assert.equal(parseDigitalProfile({ nsfwEnabled: false }).nsfwEnabled, false);
|
||||
assert.equal(parseDigitalProfile('{"nsfwEnabled":false}').nsfwEnabled, false);
|
||||
assert.equal(
|
||||
digitalUserInput.parse({
|
||||
username: "new-user",
|
||||
displayName: "新用户",
|
||||
password: "test-password",
|
||||
}).nsfwEnabled,
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
digitalUserUpdate.parse({ displayName: "用户", status: "ACTIVE" })
|
||||
.nsfwEnabled,
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
test("前台保存持久化账号偏好;旧客户端改收藏保留关闭,伪造账号不能越权", async (t) => {
|
||||
const profiles = new Map<string, Record<string, unknown>>();
|
||||
t.mock.method(authService, "getCurrentUser", async () => ({
|
||||
accountType: "DIGITAL_USER",
|
||||
}));
|
||||
t.mock.method(
|
||||
pool,
|
||||
"query",
|
||||
async (query: { sql: string }, args: unknown[]) => {
|
||||
if (query.sql.startsWith("SELECT body FROM dh_profiles"))
|
||||
return [
|
||||
profiles.has(String(args[0]))
|
||||
? [{ body: profiles.get(String(args[0])) }]
|
||||
: [],
|
||||
[],
|
||||
];
|
||||
if (query.sql.startsWith("INSERT INTO dh_profiles")) {
|
||||
assert.match(query.sql, /JSON_MERGE_PATCH/);
|
||||
const account = String(args[0]);
|
||||
profiles.set(account, {
|
||||
...profiles.get(account),
|
||||
...JSON.parse(String(args[1])),
|
||||
});
|
||||
return [{ affectedRows: 1 }, []];
|
||||
}
|
||||
if (query.sql.startsWith("SELECT")) return [[], []];
|
||||
throw new Error("未覆盖 SQL:" + query.sql);
|
||||
},
|
||||
);
|
||||
const app = createApp();
|
||||
try {
|
||||
await app.ready();
|
||||
const token = app.jwt.sign({
|
||||
sub: "user:7",
|
||||
accountType: "DIGITAL_USER",
|
||||
scene: "DIGITAL_APP",
|
||||
});
|
||||
const headers = { authorization: `Bearer ${token}` };
|
||||
const initial = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/digital/bootstrap",
|
||||
headers,
|
||||
});
|
||||
assert.equal(initial.statusCode, 200);
|
||||
assert.equal(initial.json().data.profile.nsfwEnabled, true);
|
||||
const base = { favorites: [], userName: "旅人", persona: "测试身份" };
|
||||
const disabled = await app.inject({
|
||||
method: "PUT",
|
||||
url: "/api/digital/profile",
|
||||
headers,
|
||||
payload: { ...base, nsfwEnabled: false, account: "user:999" },
|
||||
});
|
||||
assert.equal(disabled.statusCode, 200);
|
||||
assert.equal(disabled.json().data.nsfwEnabled, false);
|
||||
assert.equal(profiles.has("user:999"), false);
|
||||
const favorite = await app.inject({
|
||||
method: "PUT",
|
||||
url: "/api/digital/profile",
|
||||
headers,
|
||||
payload: { ...base, favorites: ["card"] },
|
||||
});
|
||||
assert.equal(favorite.json().data.nsfwEnabled, false);
|
||||
assert.deepEqual(favorite.json().data.favorites, ["card"]);
|
||||
const bootstrap = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/digital/bootstrap",
|
||||
headers,
|
||||
});
|
||||
assert.equal(bootstrap.json().data.profile.nsfwEnabled, false);
|
||||
const invalid = await app.inject({
|
||||
method: "PUT",
|
||||
url: "/api/digital/profile",
|
||||
headers,
|
||||
payload: { ...base, nsfwEnabled: "false" },
|
||||
});
|
||||
assert.equal(invalid.statusCode, 400);
|
||||
const enabled = await app.inject({
|
||||
method: "PUT",
|
||||
url: "/api/digital/profile",
|
||||
headers,
|
||||
payload: { ...base, nsfwEnabled: true },
|
||||
});
|
||||
assert.equal(enabled.json().data.nsfwEnabled, true);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("后台用户列表返回同一账号偏好,不附带用户身份正文", async (t) => {
|
||||
t.mock.method(pool, "query", async (query: { sql: string }) => {
|
||||
if (query.sql.includes("COUNT(*) total")) return [[{ total: 2 }], []];
|
||||
assert.match(
|
||||
query.sql,
|
||||
/LEFT JOIN dh_profiles p ON p.account=CONCAT\('user:',u.id\)/,
|
||||
);
|
||||
return [
|
||||
[
|
||||
{ id: 1, profileBody: { nsfwEnabled: false, persona: "私密身份" } },
|
||||
{ id: 2, profileBody: null },
|
||||
],
|
||||
[],
|
||||
];
|
||||
});
|
||||
const result = await digitalUsers({ q: "", page: 1, size: 20 });
|
||||
assert.equal(result.items[0].nsfwEnabled, false);
|
||||
assert.equal(result.items[1].nsfwEnabled, true);
|
||||
assert.equal(JSON.stringify(result).includes("私密身份"), false);
|
||||
});
|
||||
|
||||
test("游客不能读取或修改内容偏好,也不能通过请求体开启生成", async () => {
|
||||
const app = createApp();
|
||||
try {
|
||||
for (const request of [
|
||||
{ method: "GET" as const, url: "/api/digital/bootstrap" },
|
||||
{
|
||||
method: "PUT" as const,
|
||||
url: "/api/digital/profile",
|
||||
payload: { nsfwEnabled: true },
|
||||
},
|
||||
{
|
||||
method: "POST" as const,
|
||||
url: "/api/digital/conversations/chat/stream",
|
||||
payload: { nsfwEnabled: true },
|
||||
},
|
||||
]) {
|
||||
const response = await app.inject(request);
|
||||
assert.equal(response.statusCode, 401, request.url);
|
||||
}
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("管理员修改与本人资料使用同一账号偏好,基础资料编辑不重置开关", async (t) => {
|
||||
let profile = { favorites: ["card"], userName: "旅人", nsfwEnabled: true };
|
||||
const audits: Record<string, unknown>[] = [];
|
||||
t.mock.method(pool, "getConnection", async () => ({
|
||||
beginTransaction: async () => {},
|
||||
commit: async () => {},
|
||||
rollback: async () => {},
|
||||
release: () => {},
|
||||
query: async (query: { sql: string }, args: unknown[]) => {
|
||||
if (query.sql.startsWith("SELECT id FROM dh_users"))
|
||||
return [[{ id: 7 }], []];
|
||||
if (query.sql.startsWith("INSERT INTO dh_profiles")) {
|
||||
assert.equal(args[0], "user:7");
|
||||
assert.match(query.sql, /JSON_MERGE_PATCH/);
|
||||
profile = { ...profile, ...JSON.parse(String(args[1])) };
|
||||
}
|
||||
if (query.sql.startsWith("INSERT INTO dh_audits"))
|
||||
audits.push(JSON.parse(String(args[3])));
|
||||
return [{ affectedRows: 1 }, []];
|
||||
},
|
||||
}));
|
||||
await updateDigitalUser("super_admin:1", 7, {
|
||||
displayName: "用户甲",
|
||||
status: "ACTIVE",
|
||||
nsfwEnabled: false,
|
||||
});
|
||||
assert.equal(profile.nsfwEnabled, false);
|
||||
assert.deepEqual(profile.favorites, ["card"]);
|
||||
assert.equal(audits[0].nsfwEnabled, false);
|
||||
await updateDigitalUser("super_admin:1", 7, {
|
||||
displayName: "用户乙",
|
||||
status: "ACTIVE",
|
||||
});
|
||||
assert.equal(profile.nsfwEnabled, false);
|
||||
});
|
||||
@@ -79,3 +79,28 @@ test("灵感接口不接受匿名用户,即使请求体伪造账号也会先
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("回复灵感遵循账号开关,关闭时保留日常内容限制", () => {
|
||||
for (const nsfwEnabled of [true, false]) {
|
||||
const messages = replyIdeasMessages({
|
||||
name: "角色",
|
||||
description: "",
|
||||
scenario: "",
|
||||
userName: "旅人",
|
||||
persona: "",
|
||||
memory: "",
|
||||
draft: "",
|
||||
lore: [],
|
||||
history: [],
|
||||
nsfwEnabled,
|
||||
});
|
||||
assert.ok(
|
||||
messages[0].content.includes(nsfwEnabled ? "NSFW 已开启" : "NSFW 已关闭"),
|
||||
);
|
||||
assert.match(messages[0].content, /禁止涉及未成年人的性内容/);
|
||||
assert.equal(
|
||||
messages[0].content.includes("不生成露骨性描写"),
|
||||
!nsfwEnabled,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -53,7 +53,10 @@ test("C 端登录只查询独立用户,不从同名管理员或员工回退",
|
||||
assert.equal(result.user.canManage, false);
|
||||
exists = false;
|
||||
await assert.rejects(
|
||||
loginDigitalUser({ username: "admin", password: "unrelated-admin-password" }),
|
||||
loginDigitalUser({
|
||||
username: "admin",
|
||||
password: "unrelated-admin-password",
|
||||
}),
|
||||
/账号或密码不正确/,
|
||||
);
|
||||
});
|
||||
@@ -227,9 +230,17 @@ test("开户和重置只写 C 端密码哈希,审计不记录密码", async (t
|
||||
password: "new-user-password",
|
||||
});
|
||||
await resetDigitalPassword("super_admin:1", 7, "reset-user-password");
|
||||
const initialProfile = writes.find((w) =>
|
||||
w.sql.startsWith("INSERT INTO dh_profiles"),
|
||||
);
|
||||
assert.equal(initialProfile!.args[0], "user:7");
|
||||
assert.equal(JSON.parse(String(initialProfile!.args[1])).nsfwEnabled, true);
|
||||
assert.ok(
|
||||
writes.every(
|
||||
(w) => w.sql.includes("dh_users") || w.sql.includes("dh_audits"),
|
||||
(w) =>
|
||||
w.sql.includes("dh_users") ||
|
||||
w.sql.includes("dh_audits") ||
|
||||
w.sql.includes("dh_profiles"),
|
||||
),
|
||||
);
|
||||
for (const w of writes.filter((w) => w.sql.includes("dh_audits"))) {
|
||||
|
||||
Reference in New Issue
Block a user