import { readFileSync } from 'node:fs'; import type { ClientRequest, IncomingMessage, ServerResponse } from 'node:http'; import { homedir, hostname } from 'node:os'; import { join } from 'node:path'; import { svelte } from '@sveltejs/vite-plugin-svelte'; import { defineConfig, type Plugin, type ProxyOptions } from 'vite'; // In development the page talks to the running daemon through Vite: the proxy // reads the daemon's port and token the way the CLI does, so the browser never // holds the token. `albedo web` does the same in production. The endpoint is // read once, so restart `npm run dev` after the daemon restarts. function daemonProxy( { port, token }: Endpoint, rewrite: (path: string) => string, answer?: Record, ): ProxyOptions { return { target: `http://127.0.0.1:${port}`, ws: true, headers: { authorization: `Bearer ${token}` }, rewrite, configure(proxy) { const stripBrowserHeaders = (req: ClientRequest) => { req.removeHeader('origin'); req.removeHeader('cookie'); req.removeHeader('referer'); }; proxy.on('proxyReq', stripBrowserHeaders); proxy.on('proxyReqWs', (outgoing, incoming, socket) => { if (foreignOrigin(incoming)) { outgoing.destroy(); socket.end( 'HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n', ); return; } stripBrowserHeaders(outgoing); }); if (answer) proxy.on('proxyRes', (res) => Object.assign(res.headers, answer)); }, }; } // The proxy drops Origin and adds the token, so it checks the origin first, as // `albedo web` does: a request a browser sent from any page but the dev // server's own (a sandboxed artifact's is "null") never reaches the daemon. function foreignOrigin(incoming: IncomingMessage): boolean { const origin = incoming.headers.origin; return !!origin && origin !== `http://${incoming.headers.host}`; } // Refuses an ordinary /api request from a foreign origin before it is proxied; // Vite stops at a response that has ended. An upgrade has no response here and // is refused in proxyReqWs. /frame/ is left open as `albedo web` leaves it: an // artifact's own requests come from its opaque origin, and the key in the path // is the capability. function refuseForeignOrigin( req: IncomingMessage, res: ServerResponse | undefined, ): string | undefined { if (!res || !foreignOrigin(req)) return undefined; res .writeHead(403, { 'content-type': 'text/plain' }) .end('origin is not allowed'); return req.url; } // Artifact pages are sandboxed by the same headers `albedo web` sets on its // /frame route (robot-docs/artifacts.md), so the client is tried as it ships. const FRAME_HEADERS = { 'content-security-policy': 'sandbox allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals allow-downloads allow-pointer-lock', 'access-control-allow-origin': '*', 'cross-origin-resource-policy': 'cross-origin', 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff', }; function ownNames(): string[] { const name = hostname() .toLowerCase() .replace(/\.local$/, ''); return [name, `${name}.local`, '.ts.net']; } type Endpoint = { port: number; token: string }; /** The running daemon's port and token, or null with none running (svelte-check loads this config too, in CI). */ function daemonEndpoint(): Endpoint | null { const home = process.env.ALBEDO_HOME ?? join(homedir(), '.albedo'); try { return JSON.parse(readFileSync(join(home, 'daemon.json'), 'utf8')); } catch { return null; } } // @pierre/diffs can highlight with Shiki's regex or WASM engine or with its // own WASM highlighter, and reaches every theme each of them ships through // dynamic imports, so the build would emit them all (about 3 MB). The client // uses Shiki's regex engine and pierre-dark and pierre-light (DiffView, // FileView): the rest resolves to modules that throw if anything asks for them. const UNUSED = [ '@pierre/highlights', '@pierre/highlights/themes/loader', 'shiki/engine/oniguruma', 'shiki/wasm', ]; const UNAVAILABLE = `const fail = () => { throw new Error('not in this build: see web/vite.config.ts'); }; export const LiveTokenizer = fail, codeToTokens = fail, isSupportedLanguage = fail, createOnigurumaEngine = fail, themes = {}; export default fail;`; const PIERRE_THEMES = `import { createThemeCollection } from '@pierre/theming'; const theme = (name, colorScheme, load) => ({ name, colorScheme, collection: 'pierre', load: async () => { const [raw, { normalizeTheme }] = await Promise.all([load(), import('shiki/core')]); return normalizeTheme(raw.default ?? raw); }, }); export const themes = createThemeCollection({ themes: [theme('pierre-dark', 'dark', () => import('@pierre/theme/pierre-dark')), theme('pierre-light', 'light', () => import('@pierre/theme/pierre-light'))], });`; function trimBundle(): Plugin { return { name: 'albedo-trim-bundle', enforce: 'pre', resolveId(id) { if (UNUSED.includes(id)) return `\0unused:${id}`; if (id === '@pierre/theming/themes') return '\0pierre-themes'; }, load(id) { if (id.startsWith('\0unused:')) return UNAVAILABLE; if (id === '\0pierre-themes') return PIERRE_THEMES; }, // Every browser the client targets reads woff2, so KaTeX's woff and ttf // copies of each font are never fetched; leaving them out of its CSS keeps // them out of the build. transform(code, id) { if (id.endsWith('katex.min.css')) return code.replace( /,url\([^)]*\.(?:woff|ttf)\) format\("(?:woff|truetype)"\)/g, '', ); }, }; } // Only the dev server talks to a daemon, so a build (in the Nix sandbox, say) // never needs daemon.json. export default defineConfig(({ command }) => { const daemon = command === 'serve' ? daemonEndpoint() : null; return { plugins: [trimBundle(), svelte()], // Open to the local network, so other devices at home can try the client. // Only this machine's own names (and Tailscale's MagicDNS ones) pass as Host: // the proxy holds the daemon token, so any name a page could rebind must not. server: { host: true, allowedHosts: ownNames(), proxy: daemon ? { '/api': { ...daemonProxy(daemon, (path) => path.replace(/^\/api/, '')), bypass: refuseForeignOrigin, }, '/frame/': daemonProxy( daemon, (path) => path.replace(/^\/frame/, '/extensions/artifacts/frame'), FRAME_HEADERS, ), } : undefined, }, build: { target: 'es2022', reportCompressedSize: true }, }; });