|
| 1 | +/** |
| 2 | + * Static dev server for the browser playground. |
| 3 | + * |
| 4 | + * SharedArrayBuffer (required by the secure-exec web worker) needs COOP/COEP |
| 5 | + * headers. Once COEP is "require-corp", every subresource must be same-origin |
| 6 | + * or carry Cross-Origin-Resource-Policy. Vendor assets (Monaco, Pyodide, |
| 7 | + * TypeScript) are installed as npm packages and symlinked into vendor/ by |
| 8 | + * `scripts/setup-vendor.ts`, so everything is served from the local filesystem. |
| 9 | + */ |
| 10 | +import { createReadStream } from "node:fs"; |
| 11 | +import { realpath, stat } from "node:fs/promises"; |
| 12 | +import { |
| 13 | + createServer, |
| 14 | + type OutgoingHttpHeaders, |
| 15 | + type Server, |
| 16 | + type ServerResponse, |
| 17 | +} from "node:http"; |
| 18 | +import { extname, join, normalize, resolve } from "node:path"; |
| 19 | +import { fileURLToPath } from "node:url"; |
| 20 | + |
| 21 | +const DEFAULT_PORT = Number(process.env.PORT ?? "4173"); |
| 22 | +const playgroundDir = resolve(fileURLToPath(new URL("..", import.meta.url))); |
| 23 | +const secureExecDir = resolve(playgroundDir, "../secure-exec"); |
| 24 | + |
| 25 | +/* Map URL prefixes to filesystem directories outside playgroundDir */ |
| 26 | +const PATH_ALIASES: Array<{ prefix: string; dir: string }> = [ |
| 27 | + { prefix: "/secure-exec/", dir: secureExecDir }, |
| 28 | +]; |
| 29 | + |
| 30 | +const mimeTypes = new Map<string, string>([ |
| 31 | + [".css", "text/css; charset=utf-8"], |
| 32 | + [".data", "application/octet-stream"], |
| 33 | + [".html", "text/html; charset=utf-8"], |
| 34 | + [".js", "text/javascript; charset=utf-8"], |
| 35 | + [".json", "application/json; charset=utf-8"], |
| 36 | + [".mjs", "text/javascript; charset=utf-8"], |
| 37 | + [".svg", "image/svg+xml"], |
| 38 | + [".wasm", "application/wasm"], |
| 39 | + [".zip", "application/zip"], |
| 40 | +]); |
| 41 | + |
| 42 | +function getFilePath(urlPath: string): string | null { |
| 43 | + const pathname = decodeURIComponent(urlPath.split("?")[0] ?? "/"); |
| 44 | + const relativePath = pathname === "/" ? "/frontend/index.html" : pathname; |
| 45 | + |
| 46 | + /* Check path aliases for sibling packages (e.g. secure-exec dist) */ |
| 47 | + for (const alias of PATH_ALIASES) { |
| 48 | + if (relativePath.startsWith(alias.prefix)) { |
| 49 | + const rest = relativePath.slice(alias.prefix.length); |
| 50 | + const safePath = normalize(rest).replace(/^(\.\.[/\\])+/, ""); |
| 51 | + const absolutePath = resolve(alias.dir, safePath); |
| 52 | + if (!absolutePath.startsWith(alias.dir)) return null; |
| 53 | + return absolutePath; |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + const safePath = normalize(relativePath).replace(/^(\.\.[/\\])+/, ""); |
| 58 | + const absolutePath = resolve(playgroundDir, `.${safePath}`); |
| 59 | + if (!absolutePath.startsWith(playgroundDir)) { |
| 60 | + return null; |
| 61 | + } |
| 62 | + return absolutePath; |
| 63 | +} |
| 64 | + |
| 65 | +function getRedirectLocation(urlPath: string): string | null { |
| 66 | + const [pathname, search = ""] = urlPath.split("?"); |
| 67 | + if (pathname === "/" || pathname.endsWith("/")) { |
| 68 | + return null; |
| 69 | + } |
| 70 | + return `${pathname}/${search ? `?${search}` : ""}`; |
| 71 | +} |
| 72 | + |
| 73 | +const COEP_HEADERS = { |
| 74 | + "Cross-Origin-Embedder-Policy": "require-corp", |
| 75 | + "Cross-Origin-Opener-Policy": "same-origin", |
| 76 | +} as const; |
| 77 | + |
| 78 | +function writeHeaders(response: ServerResponse, status: number, extras: OutgoingHttpHeaders = {}): void { |
| 79 | + response.writeHead(status, { |
| 80 | + "Cache-Control": "no-store", |
| 81 | + ...COEP_HEADERS, |
| 82 | + ...extras, |
| 83 | + }); |
| 84 | +} |
| 85 | + |
| 86 | +export function createBrowserPlaygroundServer(): Server { |
| 87 | + return createServer(async (_request, response) => { |
| 88 | + const requestUrl = _request.url ?? "/"; |
| 89 | + |
| 90 | + const filePath = getFilePath(requestUrl); |
| 91 | + if (!filePath) { |
| 92 | + writeHeaders(response, 403); |
| 93 | + response.end("Forbidden"); |
| 94 | + return; |
| 95 | + } |
| 96 | + |
| 97 | + /* Resolve symlinks (vendor/ entries point into node_modules) */ |
| 98 | + let resolvedPath: string; |
| 99 | + try { |
| 100 | + resolvedPath = await realpath(filePath); |
| 101 | + } catch { |
| 102 | + writeHeaders(response, 404); |
| 103 | + response.end("Not found"); |
| 104 | + return; |
| 105 | + } |
| 106 | + |
| 107 | + let finalPath = resolvedPath; |
| 108 | + try { |
| 109 | + const fileStat = await stat(resolvedPath); |
| 110 | + if (fileStat.isDirectory()) { |
| 111 | + const redirectLocation = getRedirectLocation(requestUrl); |
| 112 | + if (redirectLocation) { |
| 113 | + writeHeaders(response, 308, { Location: redirectLocation }); |
| 114 | + response.end(); |
| 115 | + return; |
| 116 | + } |
| 117 | + finalPath = join(resolvedPath, "index.html"); |
| 118 | + } |
| 119 | + } catch { |
| 120 | + writeHeaders(response, 404); |
| 121 | + response.end("Not found"); |
| 122 | + return; |
| 123 | + } |
| 124 | + |
| 125 | + try { |
| 126 | + const fileStat = await stat(finalPath); |
| 127 | + if (!fileStat.isFile()) { |
| 128 | + writeHeaders(response, 404); |
| 129 | + response.end("Not found"); |
| 130 | + return; |
| 131 | + } |
| 132 | + |
| 133 | + const mimeType = mimeTypes.get(extname(finalPath)) ?? "application/octet-stream"; |
| 134 | + writeHeaders(response, 200, { |
| 135 | + "Content-Length": String(fileStat.size), |
| 136 | + "Content-Type": mimeType, |
| 137 | + }); |
| 138 | + createReadStream(finalPath).pipe(response); |
| 139 | + } catch { |
| 140 | + writeHeaders(response, 500); |
| 141 | + response.end("Failed to read file"); |
| 142 | + } |
| 143 | + }); |
| 144 | +} |
| 145 | + |
| 146 | +export function startBrowserPlaygroundServer(port = DEFAULT_PORT): Server { |
| 147 | + const server = createBrowserPlaygroundServer(); |
| 148 | + server.listen(port, () => { |
| 149 | + console.log(`Browser playground: http://localhost:${port}/`); |
| 150 | + }); |
| 151 | + return server; |
| 152 | +} |
| 153 | + |
| 154 | +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { |
| 155 | + startBrowserPlaygroundServer(); |
| 156 | +} |
0 commit comments