|
| 1 | +import { EventEmitter } from "node:events"; |
| 2 | +import type { IncomingMessage, ServerResponse } from "node:http"; |
| 3 | +import type { Plugin, ViteDevServer } from "vite"; |
| 4 | +import { afterEach, describe, expect, it, vi } from "vitest"; |
| 5 | +import config from "./vite.config"; |
| 6 | + |
| 7 | +const ENV = "HYPERFRAMES_PREVIEW_ALLOWED_HOSTS"; |
| 8 | + |
| 9 | +type Middleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => unknown; |
| 10 | + |
| 11 | +interface Reply { |
| 12 | + status: number | undefined; |
| 13 | + body: string; |
| 14 | +} |
| 15 | + |
| 16 | +const httpServers: EventEmitter[] = []; |
| 17 | + |
| 18 | +afterEach(() => { |
| 19 | + // Closes the plugin's project watcher. |
| 20 | + for (const httpServer of httpServers.splice(0)) httpServer.emit("close"); |
| 21 | + vi.unstubAllEnvs(); |
| 22 | +}); |
| 23 | + |
| 24 | +function devApiPlugin(): Plugin { |
| 25 | + const plugin = (config.plugins ?? []) |
| 26 | + .flat(Infinity) |
| 27 | + .find( |
| 28 | + (p): p is Plugin => |
| 29 | + typeof p === "object" && p !== null && "name" in p && p.name === "studio-dev-api", |
| 30 | + ); |
| 31 | + if (!plugin) throw new Error("studio-dev-api plugin not found"); |
| 32 | + return plugin; |
| 33 | +} |
| 34 | + |
| 35 | +// Stands in for the studio-server module so an allowed /api/ request has something to reach. |
| 36 | +function fakeStudioServerModule(): Record<string, unknown> { |
| 37 | + return { |
| 38 | + createStudioApi: () => ({ fetch: async () => Response.json({ ok: true }) }), |
| 39 | + previewAllowedHostsFromEnv: () => [], |
| 40 | + identifyFileWrite: () => null, |
| 41 | + fileContentVersion: () => "v", |
| 42 | + affectsPreview: () => true, |
| 43 | + openProjectHistory: async () => null, |
| 44 | + DELETED_VERSION: "deleted", |
| 45 | + }; |
| 46 | +} |
| 47 | + |
| 48 | +function startPlugin(): Middleware[] { |
| 49 | + const middlewares: Middleware[] = []; |
| 50 | + const httpServer = new EventEmitter(); |
| 51 | + httpServers.push(httpServer); |
| 52 | + const server = { |
| 53 | + middlewares: { use: (fn: Middleware) => void middlewares.push(fn) }, |
| 54 | + config: { server: { host: "127.0.0.1" } }, |
| 55 | + httpServer, |
| 56 | + ws: { send: () => {} }, |
| 57 | + ssrLoadModule: async () => fakeStudioServerModule(), |
| 58 | + } as unknown as ViteDevServer; |
| 59 | + const configureServer = devApiPlugin().configureServer as (s: ViteDevServer) => void; |
| 60 | + configureServer(server); |
| 61 | + return middlewares; |
| 62 | +} |
| 63 | + |
| 64 | +// Runs the request down the plugin's middlewares the way connect would; `undefined` status means every one passed it on. |
| 65 | +function request(middlewares: Middleware[], url: string, host: string): Promise<Reply> { |
| 66 | + return new Promise((resolve) => { |
| 67 | + const reply: Reply = { status: undefined, body: "" }; |
| 68 | + const res = Object.assign(new EventEmitter(), { |
| 69 | + headersSent: false, |
| 70 | + writeHead(status: number) { |
| 71 | + reply.status = status; |
| 72 | + res.headersSent = true; |
| 73 | + return res; |
| 74 | + }, |
| 75 | + write(chunk: Uint8Array | string) { |
| 76 | + reply.body += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8"); |
| 77 | + return true; |
| 78 | + }, |
| 79 | + end(chunk?: string) { |
| 80 | + if (chunk) reply.body += chunk; |
| 81 | + resolve(reply); |
| 82 | + }, |
| 83 | + }); |
| 84 | + const req = { url, method: "GET", headers: { host } } as IncomingMessage; |
| 85 | + const run = (index: number): void => { |
| 86 | + const middleware = middlewares[index]; |
| 87 | + if (!middleware) return resolve(reply); |
| 88 | + void middleware(req, res as unknown as ServerResponse, () => run(index + 1)); |
| 89 | + }; |
| 90 | + run(0); |
| 91 | + }); |
| 92 | +} |
| 93 | + |
| 94 | +describe("studio dev server host check", () => { |
| 95 | + it("refuses a foreign Host on the plugin's API and config routes", async () => { |
| 96 | + vi.stubEnv("HYPERFRAMES_PREVIEW_PROJECT_DIR", "/tmp/project"); |
| 97 | + vi.stubEnv("HYPERFRAMES_PREVIEW_PROJECT_NAME", "project"); |
| 98 | + const middlewares = startPlugin(); |
| 99 | + for (const url of ["/api/projects", "/__hyperframes_config", "/api/runtime.js"]) { |
| 100 | + const reply = await request(middlewares, url, "other.example:5190"); |
| 101 | + expect(reply.status, url).toBe(403); |
| 102 | + expect(JSON.parse(reply.body).error, url).toContain(`"other.example:5190"`); |
| 103 | + expect(JSON.parse(reply.body).error, url).toContain(ENV); |
| 104 | + } |
| 105 | + }); |
| 106 | + |
| 107 | + it("serves loopback and IP-literal hosts", async () => { |
| 108 | + vi.stubEnv("HYPERFRAMES_PREVIEW_PROJECT_DIR", "/tmp/project"); |
| 109 | + vi.stubEnv("HYPERFRAMES_PREVIEW_PROJECT_NAME", "project"); |
| 110 | + const middlewares = startPlugin(); |
| 111 | + for (const host of ["localhost:5190", "127.0.0.1:5190", "[::1]:5190", "192.168.1.20:5190"]) { |
| 112 | + expect((await request(middlewares, "/api/projects", host)).status, host).toBe(200); |
| 113 | + expect((await request(middlewares, "/__hyperframes_config", host)).status, host).toBe(200); |
| 114 | + } |
| 115 | + expect((await request(middlewares, "/api/projects", "[fe80::1]:5190")).status).toBe(200); |
| 116 | + }); |
| 117 | + |
| 118 | + it(`serves a host listed in ${ENV}`, async () => { |
| 119 | + vi.stubEnv(ENV, "studio.tunnel.example, other.tunnel.example"); |
| 120 | + const middlewares = startPlugin(); |
| 121 | + expect((await request(middlewares, "/api/projects", "studio.tunnel.example")).status).toBe(200); |
| 122 | + expect((await request(middlewares, "/api/projects", "evil.tunnel.example")).status).toBe(403); |
| 123 | + }); |
| 124 | + |
| 125 | + it("leaves routes the plugin does not own to Vite's own host check", async () => { |
| 126 | + const middlewares = startPlugin(); |
| 127 | + expect((await request(middlewares, "/", "other.example:5190")).status).toBeUndefined(); |
| 128 | + }); |
| 129 | + |
| 130 | + it(`adds ${ENV} hosts to server.allowedHosts so Vite serves the page on them`, async () => { |
| 131 | + vi.stubEnv(ENV, "studio.tunnel.example"); |
| 132 | + vi.resetModules(); |
| 133 | + const { default: fresh } = await import("./vite.config"); |
| 134 | + expect(fresh.server?.allowedHosts).toEqual(["studio.tunnel.example"]); |
| 135 | + }); |
| 136 | +}); |
0 commit comments