// Mock Cloudflare API v4 (PEP-231): DNS records of one zone and remotely managed tunnels of one // account — the calls core/edge-dns.ts makes. Envelope `{success, result, errors}` as the real API; // a wrong Bearer token → 403 with an error, like an expired token. import { randomUUID } from "node:crypto"; import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; export interface MockCfRecord { id: string; type: string; name: string; content: string; proxied?: boolean; comment?: string; } export class MockCloudflare { readonly token = "mock-cf-token"; readonly accountId = "mock-account"; readonly zoneId = "mock-zone"; records: MockCfRecord[] = []; tunnels = new Map } }>(); readonly calls: Array<{ method: string; path: string }> = []; /** Every request answers 500 (Cloudflare is down). */ down = false; private server: Server | null = null; url = ""; addRecord(r: Omit): MockCfRecord { const rec = { id: randomUUID(), ...r }; this.records.push(rec); return rec; } addTunnel(name: string, ingress: Array<{ hostname?: string; service: string }> = []): string { const id = randomUUID(); this.tunnels.set(id, { name, token: `mock-tunnel-secret-${id}`, config: { ingress } }); return id; } env(tunnelId: string): Record { return { CLOUDFLARE_API_URL: this.url, CLOUDFLARE_API_TOKEN: this.token, CLOUDFLARE_ACCOUNT_ID: this.accountId, CLOUDFLARE_ZONE_ID: this.zoneId, CLOUDFLARE_TUNNEL_ID: tunnelId }; } async start(): Promise { this.server = createServer((req, res) => { const chunks: Buffer[] = []; req.on("data", (c) => chunks.push(c)); req.on("end", () => { const u = new URL(req.url ?? "/", "http://x"); const method = req.method ?? "GET"; this.calls.push({ method, path: u.pathname }); const send = (status: number, result: unknown, errors: Array<{ code: number; message: string }> = []) => res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify({ success: status < 300, result: status < 300 ? result : null, errors, messages: [] })); if (this.down) return send(500, null, [{ code: 10000, message: "Internal error" }]); if (req.headers.authorization !== `Bearer ${this.token}`) return send(403, null, [{ code: 10000, message: "Authentication error" }]); const body = chunks.length ? (JSON.parse(Buffer.concat(chunks).toString()) as Record) : {}; let m: RegExpExecArray | null; if ((m = /^\/zones\/([^/]+)\/dns_records(?:\/([^/]+))?$/.exec(u.pathname))) { if (m[1] !== this.zoneId) return send(404, null, [{ code: 7003, message: "Could not route to /zones" }]); const id = m[2]; if (method === "GET" && !id) { const name = u.searchParams.get("name"); return send(200, this.records.filter((r) => !name || r.name === name)); } if (method === "POST" && !id) { if (this.records.some((r) => r.name === body.name && (r.type === "CNAME" || body.type === "CNAME"))) return send(400, null, [{ code: 81053, message: "An A, AAAA, or CNAME record with that host already exists." }]); return send(200, this.addRecord({ type: String(body.type), name: String(body.name), content: String(body.content), proxied: !!body.proxied, comment: body.comment as string | undefined })); } if (method === "PUT" && id) { const r = this.records.find((x) => x.id === id); if (!r) return send(404, null, [{ code: 81044, message: "Record does not exist." }]); Object.assign(r, { type: String(body.type), name: String(body.name), content: String(body.content), proxied: !!body.proxied, comment: body.comment as string | undefined }); return send(200, r); } } if ((m = /^\/accounts\/([^/]+)\/cfd_tunnel(?:\/([^/]+))?(?:\/(configurations|token))?$/.exec(u.pathname))) { if (m[1] !== this.accountId) return send(404, null, [{ code: 7003, message: "Could not route to /accounts" }]); const [, , id, sub] = m; if (method === "POST" && !id) { const tid = this.addTunnel(String(body.name)); return send(200, { id: tid, name: body.name }); } const t = id ? this.tunnels.get(id) : undefined; if (!t) return send(404, null, [{ code: 1003, message: "Tunnel not found" }]); if (sub === "token" && method === "GET") return send(200, t.token); if (sub === "configurations" && method === "GET") return send(200, { tunnel_id: id, config: t.config }); if (sub === "configurations" && method === "PUT") { t.config = (body.config as typeof t.config) ?? { ingress: [] }; return send(200, { tunnel_id: id, config: t.config }); } } send(404, null, [{ code: 7000, message: "No route for that URI" }]); }); }); await new Promise((r) => this.server!.listen(0, "127.0.0.1", r)); this.url = `http://127.0.0.1:${(this.server!.address() as AddressInfo).port}`; return this; } async stop(): Promise { await new Promise((r) => (this.server ? this.server.close(() => r()) : r())); } }