返回 CodeWhale
community-agent.test.ts
根目录 / web / lib / community-agent.test.ts
1 import { describe, it, expect, vi, beforeEach } from "vitest";
2 import { createSession, logUsage, validateSession } from "./community-agent";
3
4 describe("validateSession", () => {
5 let mockKV: {
6 get: ReturnType<typeof vi.fn>;
7 put: ReturnType<typeof vi.fn>;
8 list: ReturnType<typeof vi.fn>;
9 delete: ReturnType<typeof vi.fn>;
10 };
11
12 beforeEach(() => {
13 mockKV = {
14 get: vi.fn(),
15 put: vi.fn(),
16 list: vi.fn(),
17 delete: vi.fn(),
18 };
19 });
20
21 const VALID_SID = "a".repeat(40);
22 const SESSION_PREFIX = "session:admin:";
23 const TOKEN = "local-fixture-token-0123456789-abcdefghij";
24 const ROTATED = "rotated-fixture-token-9876543210-zyxwvutsrq";
25
26 it("should return false if kv is undefined", async () => {
27 const result = await validateSession(undefined, VALID_SID, TOKEN);
28 expect(result).toBe(false);
29 });
30
31 it("should return false if sid is undefined or null", async () => {
32 const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
33 expect(await validateSession(kv, undefined, TOKEN)).toBe(false);
34 expect(await validateSession(kv, null, TOKEN)).toBe(false);
35 });
36
37 it("should return false if sid is empty", async () => {
38 const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
39 expect(await validateSession(kv, "", TOKEN)).toBe(false);
40 });
41
42 it("should return false if sid length is less than 40", async () => {
43 const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
44 expect(await validateSession(kv, "a".repeat(39), TOKEN)).toBe(false);
45 });
46
47 it("should return false if sid length is greater than 64", async () => {
48 const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
49 expect(await validateSession(kv, "a".repeat(65), TOKEN)).toBe(false);
50 });
51
52 it("should return false if sid contains invalid characters", async () => {
53 const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
54 // Length 40 but contains invalid char '!'
55 expect(await validateSession(kv, "a".repeat(39) + "!", TOKEN)).toBe(false);
56 });
57
58 it("should return false if session is not found in KV", async () => {
59 const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
60 mockKV.get.mockResolvedValue(null);
61
62 const result = await validateSession(kv, VALID_SID, TOKEN);
63 expect(result).toBe(false);
64 expect(mockKV.get).toHaveBeenCalledWith(SESSION_PREFIX + VALID_SID);
65 });
66
67 it("should return true for a session minted under the configured token", async () => {
68 const store = new Map<string, string>();
69 const kv = {
70 get: async (key: string) => store.get(key) ?? null,
71 put: async (key: string, value: string) => { store.set(key, value); },
72 } as unknown as Parameters<typeof validateSession>[0];
73 const sid = await createSession(kv, TOKEN);
74 expect(sid).toMatch(/^[A-Za-z0-9_-]{43}$/);
75 expect(await validateSession(kv, sid, TOKEN)).toBe(true);
76 });
77
78 it("should refuse the same session once the configured token changes", async () => {
79 const store = new Map<string, string>();
80 const kv = {
81 get: async (key: string) => store.get(key) ?? null,
82 put: async (key: string, value: string) => { store.set(key, value); },
83 } as unknown as Parameters<typeof validateSession>[0];
84 const sid = await createSession(kv, TOKEN);
85 expect(await validateSession(kv, sid, ROTATED)).toBe(false);
86 expect(await validateSession(kv, sid, "short")).toBe(false);
87 expect(await validateSession(kv, sid, undefined)).toBe(false);
88 expect(await validateSession(kv, sid, TOKEN)).toBe(true);
89 });
90
91 it("should refuse a stored record with no token fingerprint or unparseable content", async () => {
92 const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
93 for (const raw of [JSON.stringify({ createdAt: Date.now() }), "{}", "not json", JSON.stringify({ tokenFingerprint: 7 })]) {
94 mockKV.get.mockResolvedValue(raw);
95 expect(await validateSession(kv, VALID_SID, TOKEN)).toBe(false);
96 }
97 });
98
99 it("should not mint a session under a weak token", async () => {
100 const kv = mockKV as unknown as Parameters<typeof createSession>[0];
101 for (const weak of [undefined, "", "short", "a".repeat(32)]) {
102 expect(await createSession(kv, weak)).toBeNull();
103 }
104 expect(mockKV.put).not.toHaveBeenCalled();
105 });
106 });
107
108 describe("logUsage", () => {
109 it("keeps every call when cron tasks log at the same time", async () => {
110 // A KV whose reads resolve before either write lands, as overlapping
111 // Worker invocations see it.
112 const store = new Map<string, string>();
113 const kv = {
114 get: async (key: string) => { await new Promise((resolve) => setTimeout(resolve, 5)); return store.get(key) ?? null; },
115 put: async (key: string, value: string) => { await new Promise((resolve) => setTimeout(resolve, 5)); store.set(key, value); },
116 } as unknown as Parameters<typeof logUsage>[0];
117 await Promise.all([logUsage(kv, 100, 10), logUsage(kv, 200, 20), logUsage(kv, 300, 30)]);
118 const records = [...store.values()].map((value) => JSON.parse(value) as { calls: number; inputTokens: number });
119 expect(records.reduce((sum, record) => sum + record.calls, 0)).toBe(3);
120 expect(records.reduce((sum, record) => sum + record.inputTokens, 0)).toBe(600);
121 expect([...store.keys()].every((key) => key.startsWith(`usage:${new Date().toISOString().slice(0, 10)}`))).toBe(true);
122 });
123 });
124
124 lines TYPESCRIPT