|
| 1 | +/* |
| 2 | +pnpm test proxy-https-to-https.test.ts |
| 3 | +
|
| 4 | +*/ |
| 5 | + |
| 6 | +import * as https from "node:https"; |
| 7 | +import * as httpProxy from "../.."; |
| 8 | +import getPort from "../get-port"; |
| 9 | +import { join } from "node:path"; |
| 10 | +import { readFile } from "node:fs/promises"; |
| 11 | +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; |
| 12 | +import { Agent, setGlobalDispatcher } from "undici"; |
| 13 | + |
| 14 | +setGlobalDispatcher(new Agent({ |
| 15 | + allowH2: true |
| 16 | +})); |
| 17 | + |
| 18 | +const fixturesDir = join(__dirname, "..", "fixtures"); |
| 19 | + |
| 20 | +describe("Basic example of proxying over HTTPS to a target HTTPS server", () => { |
| 21 | + let ports: Record<'https' | 'proxy', number>; |
| 22 | + beforeAll(async () => { |
| 23 | + // Gets ports |
| 24 | + ports = { https: await getPort(), proxy: await getPort() }; |
| 25 | + }); |
| 26 | + |
| 27 | + const servers: any = {}; |
| 28 | + let ssl: { key: string; cert: string }; |
| 29 | + |
| 30 | + it("Create the target HTTPS server", async () => { |
| 31 | + ssl = { |
| 32 | + key: await readFile(join(fixturesDir, "agent2-key.pem"), "utf8"), |
| 33 | + cert: await readFile(join(fixturesDir, "agent2-cert.pem"), "utf8"), |
| 34 | + }; |
| 35 | + servers.https = https |
| 36 | + .createServer(ssl, (_req, res) => { |
| 37 | + res.writeHead(200, { "Content-Type": "text/plain" }); |
| 38 | + res.write("hello over https\n"); |
| 39 | + res.end(); |
| 40 | + }) |
| 41 | + .listen(ports.https); |
| 42 | + }); |
| 43 | + |
| 44 | + it("Create the HTTPS proxy server", async () => { |
| 45 | + servers.proxy = httpProxy |
| 46 | + .createServer({ |
| 47 | + target: `https://localhost:${ports.https}`, |
| 48 | + ssl, |
| 49 | + // without secure false, clients will fail and this is broken: |
| 50 | + secure: false, |
| 51 | + }) |
| 52 | + .listen(ports.proxy); |
| 53 | + }); |
| 54 | + |
| 55 | + it("Use fetch to test direct non-proxied https server", async () => { |
| 56 | + const r = await (await fetch(`https://localhost:${ports.https}`)).text(); |
| 57 | + expect(r).toContain("hello over https"); |
| 58 | + }); |
| 59 | + |
| 60 | + it("Use fetch to test the proxy server", async () => { |
| 61 | + const r = await (await fetch(`https://localhost:${ports.proxy}`)).text(); |
| 62 | + expect(r).toContain("hello over https"); |
| 63 | + }); |
| 64 | + |
| 65 | + afterAll(async () => { |
| 66 | + // cleanup |
| 67 | + Object.values(servers).map((x: any) => x?.close()); |
| 68 | + }); |
| 69 | +}); |
0 commit comments