|
| 1 | +import { mkdir, writeFile } from "node:fs/promises"; |
| 2 | +import { createServer, type Server } from "node:http"; |
| 3 | +import type { AddressInfo } from "node:net"; |
| 4 | +import path from "node:path"; |
| 5 | +import { chromium, type Browser } from "playwright"; |
| 6 | +import { afterAll, beforeAll, describe, expect, it } from "vitest"; |
| 7 | +import { |
| 8 | + canRunPlaywrightChromium, |
| 9 | + installMockGateway, |
| 10 | + resolvePlaywrightChromiumExecutablePath, |
| 11 | + startControlUiE2eServer, |
| 12 | + type ControlUiE2eServer, |
| 13 | +} from "../test-helpers/control-ui-e2e.ts"; |
| 14 | + |
| 15 | +const chromiumExecutablePath = resolvePlaywrightChromiumExecutablePath(chromium.executablePath()); |
| 16 | +const chromiumAvailable = canRunPlaywrightChromium(chromiumExecutablePath); |
| 17 | +const allowMissingChromium = process.env.OPENCLAW_UI_E2E_ALLOW_MISSING_CHROMIUM === "1"; |
| 18 | +const describeControlUiE2e = chromiumAvailable || !allowMissingChromium ? describe : describe.skip; |
| 19 | +const artifactDir = path.resolve(".artifacts/control-ui-e2e/control-ui-shell-routing"); |
| 20 | +const basePath = "/control"; |
| 21 | +const forwardedHeaderBlocklist = new Set([ |
| 22 | + "connection", |
| 23 | + "content-encoding", |
| 24 | + "content-length", |
| 25 | + "transfer-encoding", |
| 26 | +]); |
| 27 | +const publicAssetPaths = new Set([ |
| 28 | + "/apple-touch-icon.png", |
| 29 | + "/favicon-32.png", |
| 30 | + "/favicon.svg", |
| 31 | + "/manifest.webmanifest", |
| 32 | +]); |
| 33 | + |
| 34 | +type BasePathProxy = { |
| 35 | + baseUrl: string; |
| 36 | + close: () => Promise<void>; |
| 37 | + requests: string[]; |
| 38 | +}; |
| 39 | + |
| 40 | +let browser: Browser; |
| 41 | +let server: ControlUiE2eServer; |
| 42 | +let proxy: BasePathProxy; |
| 43 | + |
| 44 | +async function listenOnLoopback(httpServer: Server): Promise<AddressInfo> { |
| 45 | + return new Promise((resolve, reject) => { |
| 46 | + httpServer.once("error", reject); |
| 47 | + httpServer.listen(0, "127.0.0.1", () => { |
| 48 | + const address = httpServer.address(); |
| 49 | + if (!address || typeof address === "string") { |
| 50 | + reject(new Error("Control UI base-path proxy did not expose a loopback port")); |
| 51 | + return; |
| 52 | + } |
| 53 | + resolve(address); |
| 54 | + }); |
| 55 | + }); |
| 56 | +} |
| 57 | + |
| 58 | +async function startBasePathProxy(upstreamBaseUrl: string): Promise<BasePathProxy> { |
| 59 | + const requests: string[] = []; |
| 60 | + const proxyServer = createServer((request, response) => { |
| 61 | + void (async () => { |
| 62 | + const incomingUrl = new URL(request.url ?? "/", "http://control-ui.invalid"); |
| 63 | + requests.push(incomingUrl.pathname); |
| 64 | + const hasBasePath = incomingUrl.pathname.startsWith(`${basePath}/`); |
| 65 | + if (!hasBasePath && publicAssetPaths.has(incomingUrl.pathname)) { |
| 66 | + response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }); |
| 67 | + response.end("Public assets require the configured Control UI base path"); |
| 68 | + return; |
| 69 | + } |
| 70 | + const upstreamPath = hasBasePath |
| 71 | + ? incomingUrl.pathname.slice(basePath.length) |
| 72 | + : incomingUrl.pathname; |
| 73 | + const upstreamUrl = new URL(`${upstreamPath}${incomingUrl.search}`, upstreamBaseUrl); |
| 74 | + const upstream = await fetch(upstreamUrl, { |
| 75 | + headers: { Accept: request.headers.accept ?? "*/*" }, |
| 76 | + method: request.method, |
| 77 | + // Let Chromium observe redirects so the proxy cannot hide a root-mount regression. |
| 78 | + redirect: "manual", |
| 79 | + }); |
| 80 | + response.statusCode = upstream.status; |
| 81 | + for (const [name, value] of upstream.headers) { |
| 82 | + if (!forwardedHeaderBlocklist.has(name)) { |
| 83 | + response.setHeader(name, value); |
| 84 | + } |
| 85 | + } |
| 86 | + if (request.method === "HEAD") { |
| 87 | + response.end(); |
| 88 | + return; |
| 89 | + } |
| 90 | + let body = Buffer.from(await upstream.arrayBuffer()); |
| 91 | + if ( |
| 92 | + incomingUrl.pathname.startsWith(`${basePath}/`) && |
| 93 | + upstream.headers.get("content-type")?.startsWith("text/html") |
| 94 | + ) { |
| 95 | + body = Buffer.from( |
| 96 | + body |
| 97 | + .toString("utf8") |
| 98 | + .replace("<html", `<html data-openclaw-control-ui-base-path="${basePath}"`), |
| 99 | + ); |
| 100 | + } |
| 101 | + response.end(body); |
| 102 | + })().catch((error: unknown) => { |
| 103 | + response.writeHead(502, { "Content-Type": "text/plain; charset=utf-8" }); |
| 104 | + response.end(error instanceof Error ? error.message : String(error)); |
| 105 | + }); |
| 106 | + }); |
| 107 | + |
| 108 | + const address = await listenOnLoopback(proxyServer); |
| 109 | + return { |
| 110 | + baseUrl: `http://127.0.0.1:${address.port}/`, |
| 111 | + close: () => |
| 112 | + new Promise<void>((resolve, reject) => { |
| 113 | + proxyServer.close((error) => (error ? reject(error) : resolve())); |
| 114 | + }), |
| 115 | + requests, |
| 116 | + }; |
| 117 | +} |
| 118 | + |
| 119 | +describeControlUiE2e("Control UI shell routing E2E", () => { |
| 120 | + beforeAll(async () => { |
| 121 | + if (!chromiumAvailable) { |
| 122 | + throw new Error(`Playwright Chromium is unavailable at ${chromiumExecutablePath}`); |
| 123 | + } |
| 124 | + await mkdir(artifactDir, { recursive: true }); |
| 125 | + server = await startControlUiE2eServer(undefined, { source: true }); |
| 126 | + proxy = await startBasePathProxy(server.baseUrl); |
| 127 | + browser = await chromium.launch({ executablePath: chromiumExecutablePath }); |
| 128 | + }); |
| 129 | + |
| 130 | + afterAll(async () => { |
| 131 | + await browser?.close(); |
| 132 | + await proxy?.close(); |
| 133 | + await server?.close(); |
| 134 | + }); |
| 135 | + |
| 136 | + it("opens a base-path route and connects to the confirmed alternate Gateway URL", async () => { |
| 137 | + const context = await browser.newContext({ |
| 138 | + locale: "en-US", |
| 139 | + recordVideo: { dir: artifactDir, size: { height: 720, width: 1280 } }, |
| 140 | + serviceWorkers: "block", |
| 141 | + viewport: { height: 720, width: 1280 }, |
| 142 | + }); |
| 143 | + const page = await context.newPage(); |
| 144 | + const explicitGatewayUrl = "ws://127.0.0.1:29991/alternate"; |
| 145 | + const gateway = await installMockGateway(page, { basePath }); |
| 146 | + |
| 147 | + try { |
| 148 | + const url = new URL(`${basePath}/chat`, proxy.baseUrl); |
| 149 | + url.hash = new URLSearchParams({ gatewayUrl: explicitGatewayUrl }).toString(); |
| 150 | + const response = await page.goto(url.href, { waitUntil: "domcontentloaded" }); |
| 151 | + expect(response?.status()).toBe(200); |
| 152 | + |
| 153 | + const confirmation = page.locator("openclaw-gateway-url-confirmation"); |
| 154 | + await confirmation.waitFor(); |
| 155 | + expect(await confirmation.getByText(explicitGatewayUrl, { exact: true }).count()).toBe(1); |
| 156 | + await confirmation.getByRole("button", { name: "Confirm", exact: true }).click(); |
| 157 | + |
| 158 | + await gateway.waitForRequest("connect"); |
| 159 | + await page.locator("openclaw-app-shell").waitFor(); |
| 160 | + await page.locator("openclaw-chat-page").waitFor(); |
| 161 | + |
| 162 | + expect(new URL(page.url()).pathname).toBe(`${basePath}/chat/main`); |
| 163 | + expect(new URL(page.url()).hash).toBe(""); |
| 164 | + expect((await gateway.getSocketUrls()).at(-1)).toBe(explicitGatewayUrl); |
| 165 | + expect(await page.locator("html").getAttribute("data-openclaw-control-ui-base-path")).toBe( |
| 166 | + basePath, |
| 167 | + ); |
| 168 | + |
| 169 | + // The proxy rejects root asset fallbacks. Assert the rewritten DOM and |
| 170 | + // request paths so only main.ts can make these links load under the base path. |
| 171 | + const assetResults = await page.evaluate(async () => { |
| 172 | + const links = Array.from( |
| 173 | + document.querySelectorAll<HTMLLinkElement>( |
| 174 | + 'link[rel="icon"], link[rel="apple-touch-icon"], link[rel="manifest"]', |
| 175 | + ), |
| 176 | + ); |
| 177 | + return Promise.all( |
| 178 | + links.map(async (link) => { |
| 179 | + const assetResponse = await fetch(link.href, { credentials: "include" }); |
| 180 | + return { |
| 181 | + contentType: assetResponse.headers.get("content-type") ?? "", |
| 182 | + pathname: new URL(link.href).pathname, |
| 183 | + rel: link.rel, |
| 184 | + status: assetResponse.status, |
| 185 | + type: link.type, |
| 186 | + }; |
| 187 | + }), |
| 188 | + ); |
| 189 | + }); |
| 190 | + expect(assetResults).toEqual( |
| 191 | + expect.arrayContaining([ |
| 192 | + expect.objectContaining({ |
| 193 | + contentType: expect.stringContaining("image/svg+xml"), |
| 194 | + pathname: `${basePath}/favicon.svg`, |
| 195 | + rel: "icon", |
| 196 | + status: 200, |
| 197 | + type: "image/svg+xml", |
| 198 | + }), |
| 199 | + expect.objectContaining({ |
| 200 | + contentType: expect.stringContaining("image/png"), |
| 201 | + pathname: `${basePath}/favicon-32.png`, |
| 202 | + rel: "icon", |
| 203 | + status: 200, |
| 204 | + type: "image/png", |
| 205 | + }), |
| 206 | + expect.objectContaining({ |
| 207 | + contentType: expect.stringContaining("image/png"), |
| 208 | + pathname: `${basePath}/apple-touch-icon.png`, |
| 209 | + rel: "apple-touch-icon", |
| 210 | + status: 200, |
| 211 | + }), |
| 212 | + expect.objectContaining({ |
| 213 | + contentType: expect.stringContaining("application/manifest+json"), |
| 214 | + pathname: `${basePath}/manifest.webmanifest`, |
| 215 | + rel: "manifest", |
| 216 | + status: 200, |
| 217 | + }), |
| 218 | + ]), |
| 219 | + ); |
| 220 | + expect(proxy.requests).toEqual( |
| 221 | + expect.arrayContaining([ |
| 222 | + `${basePath}/chat`, |
| 223 | + `${basePath}/favicon.svg`, |
| 224 | + `${basePath}/favicon-32.png`, |
| 225 | + `${basePath}/apple-touch-icon.png`, |
| 226 | + `${basePath}/manifest.webmanifest`, |
| 227 | + ]), |
| 228 | + ); |
| 229 | + const unprefixedPublicAssetRequests = proxy.requests.filter((requestPath) => |
| 230 | + publicAssetPaths.has(requestPath), |
| 231 | + ); |
| 232 | + expect(unprefixedPublicAssetRequests).toEqual([]); |
| 233 | + |
| 234 | + await page.screenshot({ |
| 235 | + fullPage: true, |
| 236 | + path: path.join(artifactDir, "connected-shell.png"), |
| 237 | + }); |
| 238 | + await writeFile( |
| 239 | + path.join(artifactDir, "behavior-summary.json"), |
| 240 | + `${JSON.stringify( |
| 241 | + { |
| 242 | + basePath, |
| 243 | + finalPathname: new URL(page.url()).pathname, |
| 244 | + gatewayUrl: explicitGatewayUrl, |
| 245 | + publicAssetLinks: assetResults, |
| 246 | + proxyRequestPaths: [ |
| 247 | + ...new Set( |
| 248 | + proxy.requests.filter((requestPath) => requestPath.startsWith(`${basePath}/`)), |
| 249 | + ), |
| 250 | + ].toSorted(), |
| 251 | + schemaVersion: 1, |
| 252 | + unprefixedPublicAssetRequests, |
| 253 | + }, |
| 254 | + null, |
| 255 | + 2, |
| 256 | + )}\n`, |
| 257 | + ); |
| 258 | + } finally { |
| 259 | + await context.close(); |
| 260 | + } |
| 261 | + }); |
| 262 | +}); |
0 commit comments