feat: 采集 LLM token 用量并上报 lpt-be

- 客户端解析上游 usage(含 DeepSeek 缓存命中/未命中),跨重试累加
- 新增计价表(三档单价 + 峰谷时段),费用在结算时冻结
- 新增用量上报与本地 outbox 重试;4xx 判定为确定性拒绝,不无限重试
- 面板补充 Token/费用/调用次数与计价快照
- 顺带修复面板内联脚本转义错误(模板字面量吃掉 \n 与 \',面板一直空白)
This commit is contained in:
2026-10-10 18:46:01 +08:00
parent fd1193a66f
commit 935f4781a4
24 changed files with 2632 additions and 65 deletions
+84 -1
View File
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it } from "vitest";
import { checkToken, configuredToken, TOKEN_HEADER } from "./auth.js";
import { checkToken, configuredToken, providedToken, queryTokenMatches, readCookie, TOKEN_COOKIE, TOKEN_HEADER } from "./auth.js";
/** 极简 reply 替身:记录是否写出 401 */
const makeReply = () => {
@@ -70,4 +70,87 @@ describe("AI 入站令牌", () => {
expect(configuredToken()).toBe("");
expect(checkToken({ headers: {} }, makeReply())).toBe(true);
});
it("支持 cookie 传令牌:面板 HTML 与它后续的 fetch 是两个独立请求", () => {
process.env.LPT_AI_TOKEN = "secret-token";
const reply = makeReply();
expect(
checkToken({ headers: { cookie: `${TOKEN_COOKIE}=secret-token` } }, reply),
).toBe(true);
expect(reply.calls).toEqual([]);
});
it("cookie 与其它 cookie 混在一起时仍能取出令牌", () => {
process.env.LPT_AI_TOKEN = "secret-token";
const reply = makeReply();
expect(
checkToken(
{ headers: { cookie: `a=1; ${TOKEN_COOKIE}=secret-token; b=2` } },
reply,
),
).toBe(true);
});
it("header 优先于 cookie,避免旧 cookie 把新令牌挡在门外", () => {
process.env.LPT_AI_TOKEN = "new-token";
const reply = makeReply();
expect(
checkToken(
{ headers: { [TOKEN_HEADER]: "new-token", cookie: `${TOKEN_COOKIE}=old-token` } },
reply,
),
).toBe(true);
});
});
describe("readCookie", () => {
it("取出 URL 编码的值", () => {
expect(readCookie("t=a%20b", "t")).toBe("a b");
});
it("编码非法时退回原值,不抛异常", () => {
expect(readCookie("t=%E0%A4%A", "t")).toBe("%E0%A4%A");
});
it("缺失时返回 undefined", () => {
expect(readCookie(undefined, "t")).toBeUndefined();
expect(readCookie("a=1", "t")).toBeUndefined();
expect(readCookie("novalue", "t")).toBeUndefined();
});
});
describe("providedToken", () => {
it("按 header → query → cookie 的优先级取值", () => {
process.env.LPT_AI_TOKEN = "secret-token";
expect(
providedToken({
headers: { [TOKEN_HEADER]: "from-header", cookie: `${TOKEN_COOKIE}=from-cookie` },
query: { token: "from-query" },
}),
).toBe("from-header");
expect(
providedToken({ headers: {}, query: { token: "from-query" } }),
).toBe("from-query");
expect(
providedToken({ headers: { cookie: `${TOKEN_COOKIE}=from-cookie` } }),
).toBe("from-cookie");
expect(providedToken({ headers: {} })).toBe("");
});
});
describe("queryTokenMatches", () => {
it("仅在 query 令牌正确时返回 true,用于决定要不要下发 cookie", () => {
process.env.LPT_AI_TOKEN = "secret-token";
expect(queryTokenMatches({ query: { token: "secret-token" } })).toBe(true);
expect(queryTokenMatches({ query: { token: "wrong" } })).toBe(false);
expect(queryTokenMatches({})).toBe(false);
});
it("未配置令牌时不下发 cookie", () => {
delete process.env.LPT_AI_TOKEN;
expect(queryTokenMatches({ query: { token: "" } })).toBe(false);
});
});