| 1 | import assert from "node:assert/strict"; |
| 2 | import { test } from "node:test"; |
| 3 | |
| 4 | import { chatClient } from "@g1t/contracts/chat"; |
| 5 | |
| 6 | import { fromInternet, internalAnswer, type InternalChat } from "./internal.ts"; |
| 7 | |
| 8 | function service() { |
| 9 | const calls: string[] = []; |
| 10 | const chat: InternalChat = { |
| 11 | internalG1tPost: async () => (calls.push("post"), { ok: true, value: null }), |
| 12 | internalG1tEdit: async () => (calls.push("edit"), { ok: true, value: null }), |
| 13 | }; |
| 14 | return { chat, calls }; |
| 15 | } |
| 16 | |
| 17 | const call = (headers: Record<string, string> = {}) => |
| 18 | new Request("https://service/internal/g1t_post", { method: "POST", headers: { "content-type": "application/json", ...headers }, body: "{}" }); |
| 19 | |
| 20 | test("posting as g1t is refused for anything that came in from the internet", async () => { |
| 21 | for (const header of ["cf-connecting-ip", "x-real-ip", "x-forwarded-for"]) { |
| 22 | const { chat, calls } = service(); |
| 23 | const response = await internalAnswer(chat, call({ [header]: "203.0.113.9" }), "g1t_post"); |
| 24 | assert.equal(response.status, 403, header); |
| 25 | assert.deepEqual(calls, []); |
| 26 | } |
| 27 | }); |
| 28 | |
| 29 | test("a service binding's call posts and edits as g1t; anything else is not found", async () => { |
| 30 | const { chat, calls } = service(); |
| 31 | assert.equal(fromInternet(call()), false); |
| 32 | assert.equal((await internalAnswer(chat, call(), "g1t_post")).status, 200); |
| 33 | assert.equal((await internalAnswer(chat, call(), "g1t_edit")).status, 200); |
| 34 | assert.equal((await internalAnswer(chat, call(), "post")).status, 404); |
| 35 | assert.deepEqual(calls, ["post", "edit"]); |
| 36 | }); |
| 37 | |
| 38 | test("the site's chat client never reaches the internal methods", async () => { |
| 39 | const urls: string[] = []; |
| 40 | const binding = { fetch: async (url: string) => (urls.push(String(url)), Response.json({ ok: true, value: null })) }; |
| 41 | const client = chatClient(binding as never); |
| 42 | const viewer = { id: "u1", username: "ana", workspaces: [{ slug: "acme", role: "member" as const }] }; |
| 43 | await client.post("acme", "chn_1", viewer as never, { body: "hi" }); |
| 44 | await client.g1tDm("acme", viewer as never); |
| 45 | await client.g1tReset("acme", "chn_1", viewer as never); |
| 46 | await client.g1tRetry("acme", "chn_1", viewer as never); |
| 47 | await client.g1tStop("acme", "chn_1", viewer as never); |
| 48 | assert.ok(urls.every((url) => url.startsWith("https://service/rpc/")), urls.join(" ")); |
| 49 | }); |