b7433acba4
新增角色探索、收藏、世界书和身份资料;接入流式打字、停止重生成、固定记忆、会话分支与导出;适配手机和桌面并保持实验只由后台控制。
95 lines
3.1 KiB
TypeScript
95 lines
3.1 KiB
TypeScript
/** 数字人 BFF:HttpOnly 会话只在服务端转发,白名单阻止前台访问实验管理。 */
|
|
import { getBackendBaseUrl } from "@/lib/backend";
|
|
import { getSessionToken } from "@/lib/session";
|
|
|
|
/** 限制 BFF 接收体积,后端校验之前也不会无界缓存请求。 */
|
|
async function readBody(request: Request) {
|
|
if (!request.body) return undefined;
|
|
const reader = request.body.getReader(),
|
|
decoder = new TextDecoder();
|
|
let bytes = 0,
|
|
body = "";
|
|
try {
|
|
for (;;) {
|
|
const { value, done } = await reader.read();
|
|
if (done) break;
|
|
bytes += value.byteLength;
|
|
if (bytes > 65536) {
|
|
await reader.cancel();
|
|
throw new RangeError("请求内容过长");
|
|
}
|
|
body += decoder.decode(value, { stream: true });
|
|
}
|
|
return body + decoder.decode();
|
|
} finally {
|
|
reader.releaseLock();
|
|
}
|
|
}
|
|
/** 私有会话不缓存;取消下游请求会中断上游 SSE。 */
|
|
async function proxy(
|
|
request: Request,
|
|
context: { params: Promise<{ path: string[] }> },
|
|
) {
|
|
const { path } = await context.params;
|
|
const joined = path.join("/");
|
|
if (
|
|
!/^(bootstrap|profile|exposure|conversations(?:\/[a-zA-Z0-9_-]+(?:\/(?:stream|stop|branch|messages\/[a-zA-Z0-9_-]+))?)?)$/.test(
|
|
joined,
|
|
)
|
|
)
|
|
return Response.json({ message: "接口不存在" }, { status: 404 });
|
|
if (request.method !== "GET") {
|
|
const origin = request.headers.get("origin");
|
|
try {
|
|
if (!origin || new URL(origin).host !== request.headers.get("host"))
|
|
return Response.json({ message: "请求来源不合法" }, { status: 403 });
|
|
} catch {
|
|
return Response.json({ message: "请求来源不合法" }, { status: 403 });
|
|
}
|
|
}
|
|
const token = await getSessionToken();
|
|
if (!token) return Response.json({ message: "请先登录" }, { status: 401 });
|
|
const headers = new Headers({
|
|
Authorization: `Bearer ${token}`,
|
|
"Content-Type": "application/json",
|
|
});
|
|
try {
|
|
const response = await fetch(
|
|
`${getBackendBaseUrl().replace(/\/$/, "")}/digital/${joined}`,
|
|
{
|
|
method: request.method,
|
|
headers,
|
|
body: request.method === "GET" ? undefined : await readBody(request),
|
|
cache: "no-store",
|
|
signal: request.signal,
|
|
},
|
|
);
|
|
return new Response(response.body, {
|
|
status: response.status,
|
|
headers: {
|
|
"Content-Type":
|
|
response.headers.get("content-type") ?? "application/json",
|
|
"Cache-Control": "no-store, no-transform",
|
|
"X-Accel-Buffering": "no",
|
|
},
|
|
});
|
|
} catch (error) {
|
|
if (error instanceof RangeError)
|
|
return Response.json({ message: error.message }, { status: 413 });
|
|
return Response.json(
|
|
{ message: "连接暂时不可用,请稍后重试" },
|
|
{ status: 502 },
|
|
);
|
|
}
|
|
}
|
|
/** 转发前台读取。 */
|
|
export const GET = proxy;
|
|
/** 转发创建与生成。 */
|
|
export const POST = proxy;
|
|
/** 转发用户资料保存。 */
|
|
export const PUT = proxy;
|
|
/** 转发会话偏好和固定记忆。 */
|
|
export const PATCH = proxy;
|
|
/** 转发用户自己的会话删除。 */
|
|
export const DELETE = proxy;
|