import { EventEmitter } from "events"; import type { ClientRequest } from "http"; import { createViteProxy, DEFAULT_PROXY_PATHS } from "../../src/vite/proxy"; const authHeaders = { "X-UserToken": "tok", Cookie: "JSESSIONID=abc" }; const credential = { getUrl: () => new URL("https://dev12345.service-now.com/"), getHeaders: async () => authHeaders, } as any; // Stands in for the http-proxy server Vite hands to `configure`, so a test can // emit either lifecycle event and read back the headers set on the request. const configureProxy = (options: any) => { const proxyServer = new EventEmitter(); options.configure?.(proxyServer, options); return (event: "proxyReq" | "proxyReqWs") => { const headers: Record = {}; const proxyReq = { setHeader: (key: string, value: unknown) => { headers[key] = value; }, } as unknown as ClientRequest; proxyServer.emit(event, proxyReq); return headers; }; }; describe("createViteProxy", () => { test("returns an empty proxy when there is no usable credential", async () => { expect(await createViteProxy(undefined)).toEqual({}); expect(await createViteProxy({} as any)).toEqual({}); }); test("targets the instance for every default path", async () => { const proxy = await createViteProxy(credential); expect(Object.keys(proxy)).toEqual(DEFAULT_PROXY_PATHS); for (const options of Object.values(proxy)) { // Trailing slash trimmed so the path is not joined onto a double slash. expect(options).toMatchObject({ target: "https://dev12345.service-now.com", changeOrigin: true, }); } }); test("attaches auth headers to plain HTTP requests", async () => { const proxy = await createViteProxy(credential); expect(configureProxy(proxy["/api"])("proxyReq")).toEqual(authHeaders); }); // /amb is the only upgraded route, and `changeOrigin` does not cover the // WebSocket Origin header. Without `rewriteWsOrigin` the browser's // localhost origin reaches the instance, which answers the handshake with a // 403 HTML page instead of a 101; Vite writes that page to a socket the // browser has already closed and logs "ws proxy socket error: write EPIPE". test("marks /amb as a WebSocket route and rewrites its origin", async () => { const proxy = await createViteProxy(credential); expect(proxy["/amb"]).toMatchObject({ ws: true, rewriteWsOrigin: true }); for (const path of DEFAULT_PROXY_PATHS.filter((p) => p !== "/amb")) { expect(proxy[path].ws).toBeUndefined(); expect(proxy[path].rewriteWsOrigin).toBeUndefined(); } }); // An upgrade emits "proxyReqWs", never "proxyReq". Miss it and the AMB socket // opens unauthenticated and every subscription is rejected_by_glide with 403. test("attaches auth headers to the WebSocket upgrade", async () => { const proxy = await createViteProxy(credential); expect(configureProxy(proxy["/amb"])("proxyReqWs")).toEqual(authHeaders); }); });