clone

nostr relays on demand at <name>.bind.ws: claim one with your key, pay in zaps past the free allowance

dependabot/github_actions/actions-9b61906d8b
bindws / test / unit / edge.test.ts
edge.test.ts 2.2K
1// The edge without Cloudflare (docs/16-hosting-without-cloudflare.md): the2// client's address comes from the proxy's header or not at all, and the3// lease door keeps its own count when there are no rate limit bindings.4import { describe, it, expect } from "vitest";5import { clientIP, leaseAllowed, LEASES_PER_IP_MINUTE } from "../../src/edge.ts";67const req = (headers: Record<string, string>) => new Request("http://x/", { headers });89describe("the client's address", () => {10 it("is cf-connecting-ip by default, the named header's last entry elsewhere, and unknown when the header is empty", () => {11 expect(clientIP(req({ "cf-connecting-ip": "1.2.3.4", "x-forwarded-for": "9.9.9.9" }), {})).toBe("1.2.3.4");12 expect(clientIP(req({}), {})).toBe("unknown");13 expect(clientIP(req({ "x-forwarded-for": "9.9.9.9, 10.0.0.7" }), { CLIENT_IP_HEADER: "x-forwarded-for" })).toBe("10.0.0.7");14 expect(clientIP(req({ "x-real-ip": "2001:db8::1" }), { CLIENT_IP_HEADER: "x-real-ip" })).toBe("2001:db8::1");15 expect(clientIP(req({ "x-forwarded-for": "" }), { CLIENT_IP_HEADER: "x-forwarded-for" })).toBe("unknown");16 // Empty: nothing a client sends counts as an address.17 expect(clientIP(req({ "cf-connecting-ip": "1.2.3.4", "x-forwarded-for": "9.9.9.9" }), { CLIENT_IP_HEADER: "" })).toBe("unknown");18 });19});2021describe("the lease door without rate limit bindings", () => {22 it("allows a few per address per minute and then refuses, per address", async () => {23 const none = {};24 for (let i = 0; i < LEASES_PER_IP_MINUTE; i++) expect(await leaseAllowed(none, "203.0.113.1")).toBe(true);25 expect(await leaseAllowed(none, "203.0.113.1")).toBe(false);26 expect(await leaseAllowed(none, "203.0.113.2")).toBe(true);27 });2829 it("uses the bindings when both exist", async () => {30 const calls: string[] = [];31 const binding = (ok: boolean): RateLimit => ({ limit: async ({ key }) => (calls.push(key), { success: ok }) });32 expect(await leaseAllowed({ LEASE_LIMIT_IP: binding(true), LEASE_LIMIT_ALL: binding(true) }, "203.0.113.9")).toBe(true);33 expect(await leaseAllowed({ LEASE_LIMIT_IP: binding(true), LEASE_LIMIT_ALL: binding(false) }, "203.0.113.9")).toBe(false);34 expect(calls).toEqual(["203.0.113.9", "all", "203.0.113.9", "all"]);35 });36});