Files
next-ai-draw-io/tests/unit/client-ip.test.ts
T
dayuan.jiang 1333ed68c6 test: shared e2e helpers, vi.stubEnv, drop placeholder specs
- tests/e2e/lib: openApp(page, { path, config }), MODEL_CONFIGS_KEY,
  savedModelConfigs, settingsDialog, chunkedReplies, sse() and
  toolCallEvents() replace about 70 copies of goto + wait for iframe,
  three local openApp functions, 14 window.fetch overrides and the
  Node-side SSE serialisers; unused fixtures removed
- delete theme, save, history, model-config, upload and copy-paste
  specs (the copy-button test moves to chat.spec.ts); trim
  iframe-interaction, history-restore, keyboard and smoke to tests that
  can fail; file-upload asserts on the preview image
- settings-review-fixes.spec.ts split by topic into settings-bedrock,
  settings-tabs-sync and settings-providers
- unit tests use vi.stubEnv with unstubEnvs: true instead of
  hand-written process.env save and restore loops
2026-10-12 09:11:25 +09:00

59 lines
1.9 KiB
TypeScript

import { NextRequest } from "next/server"
import { describe, expect, it, vi } from "vitest"
import { getUserIdFromRequest } from "@/lib/user-id"
import { proxy } from "@/proxy"
const idFor = (ip: string) => `user-${Buffer.from(ip).toString("base64url")}`
describe("getUserIdFromRequest", () => {
const req = new Request("http://localhost/api/chat", {
headers: {
"x-forwarded-for": "203.0.113.9, 198.51.100.7",
"cf-connecting-ip": "198.51.100.7",
},
})
it("uses the first X-Forwarded-For entry by default", () => {
expect(getUserIdFromRequest(req)).toBe(idFor("203.0.113.9"))
})
it("uses CLIENT_IP_HEADER when set", () => {
vi.stubEnv("CLIENT_IP_HEADER", "cf-connecting-ip")
expect(getUserIdFromRequest(req)).toBe(idFor("198.51.100.7"))
})
it("is anonymous when the configured header is missing", () => {
vi.stubEnv("CLIENT_IP_HEADER", "cf-connecting-ip")
expect(
getUserIdFromRequest(new Request("http://localhost/api/chat")),
).toBe("anonymous")
})
})
describe("ORIGIN_SECRET", () => {
const call = (path: string, secret?: string) =>
proxy(
new NextRequest(`http://localhost${path}`, {
headers: secret ? { "x-origin-secret": secret } : {},
}),
)
it("lets every API call through when unset", () => {
expect(call("/api/chat")).toBeUndefined()
})
it("refuses API calls without the right header", async () => {
vi.stubEnv("ORIGIN_SECRET", "s3cret")
for (const res of [call("/api/chat"), call("/api/chat", "wrong")]) {
expect(res?.status).toBe(403)
}
expect(call("/api/chat", "s3cret")).toBeUndefined()
})
it("leaves pages alone, such as the health check on /", () => {
vi.stubEnv("ORIGIN_SECRET", "s3cret")
expect(call("/")?.status).toBe(307)
expect(call("/en")).toBeUndefined()
})
})