feat: 加固标题抓取并加上限流与可选入站令牌
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { checkToken, configuredToken, TOKEN_HEADER } from "./auth.js";
|
||||
|
||||
/** 极简 reply 替身:记录是否写出 401 */
|
||||
const makeReply = () => {
|
||||
const calls: number[] = [];
|
||||
return {
|
||||
calls,
|
||||
status(code: number) {
|
||||
calls.push(code);
|
||||
return { send: (body: unknown) => body };
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const original = process.env.LPT_AI_TOKEN;
|
||||
|
||||
afterEach(() => {
|
||||
if (original === undefined) {
|
||||
delete process.env.LPT_AI_TOKEN;
|
||||
} else {
|
||||
process.env.LPT_AI_TOKEN = original;
|
||||
}
|
||||
});
|
||||
|
||||
describe("AI 入站令牌", () => {
|
||||
it("未配置令牌时放行,保持开发环境零摩擦", () => {
|
||||
delete process.env.LPT_AI_TOKEN;
|
||||
expect(configuredToken()).toBe("");
|
||||
|
||||
const reply = makeReply();
|
||||
expect(checkToken({ headers: {} }, reply)).toBe(true);
|
||||
expect(reply.calls).toEqual([]);
|
||||
});
|
||||
|
||||
it("配置令牌后,缺令牌的请求被拒绝", () => {
|
||||
process.env.LPT_AI_TOKEN = "secret-token";
|
||||
const reply = makeReply();
|
||||
|
||||
expect(checkToken({ headers: {} }, reply)).toBe(false);
|
||||
expect(reply.calls).toEqual([401]);
|
||||
});
|
||||
|
||||
it("配置令牌后,header 提供正确令牌放行", () => {
|
||||
process.env.LPT_AI_TOKEN = "secret-token";
|
||||
const reply = makeReply();
|
||||
|
||||
expect(checkToken({ headers: { [TOKEN_HEADER]: "secret-token" } }, reply)).toBe(true);
|
||||
expect(reply.calls).toEqual([]);
|
||||
});
|
||||
|
||||
it("支持用 query 传令牌(便于在浏览器里打开 /admin)", () => {
|
||||
process.env.LPT_AI_TOKEN = "secret-token";
|
||||
const reply = makeReply();
|
||||
|
||||
expect(checkToken({ headers: {}, query: { token: "secret-token" } }, reply)).toBe(true);
|
||||
});
|
||||
|
||||
it("令牌错误被拒绝", () => {
|
||||
process.env.LPT_AI_TOKEN = "secret-token";
|
||||
const reply = makeReply();
|
||||
|
||||
expect(checkToken({ headers: { [TOKEN_HEADER]: "wrong" } }, reply)).toBe(false);
|
||||
expect(reply.calls).toEqual([401]);
|
||||
});
|
||||
|
||||
it("空白令牌视为未配置", () => {
|
||||
process.env.LPT_AI_TOKEN = " ";
|
||||
expect(configuredToken()).toBe("");
|
||||
expect(checkToken({ headers: {} }, makeReply())).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user