import * as fs from 'node:fs' import * as http from 'node:http' import * as path from 'node:path' import { Connector } from '@toa.io/core' import { console } from 'openspan' import { UI_PATH } from '@toa.io/definitions/extensions.configuration' /** * Serves the configuration UI: the directory `ui` builds, and nothing else. * * The page is a single-page application whose mount path is baked into the bundle, * so this server routes relative to `UI_PATH` — which is also what the ingress * forwards. `/configuration/*` is left alone: that is the component's own API. */ export class UI extends Connector { private readonly server: http.Server = http.createServer() private readonly port: number private readonly root: string public constructor(port: number, root: string = SITE) { super() this.port = port this.root = root this.server.on('request', (request, response) => { this.listen(request, response) }) } protected override async open(): Promise { /* * A taken port is a real error: uniqueness across services is settled at export * time, so nothing here has to negotiate for one. */ await new Promise((resolve, reject) => { const failed = (error: Error): void => { this.server.off('listening', listening) reject(error) } const listening = (): void => { this.server.off('error', failed) resolve() } this.server.once('error', failed) this.server.once('listening', listening) this.server.listen(this.port) }) if (!isFile(path.join(this.root, 'index.html'))) console.warn('Configuration UI is not built', { root: this.root }) console.info('Configuration UI started', { port: this.port, path: UI_PATH + '/' }) } protected override async close(): Promise { const closed = new Promise((resolve) => this.server.once('close', () => { resolve() }) ) this.server.close() this.server.closeAllConnections() await closed } private listen(request: http.IncomingMessage, response: http.ServerResponse): void { void this.respond(request, response).catch((error: Error) => { console.error('Configuration UI failure', { message: error.message }) if (!response.writableEnded) response.writeHead(500).end() }) } private async respond( request: http.IncomingMessage, response: http.ServerResponse ): Promise { if (request.method !== 'GET' && request.method !== 'HEAD') { response.writeHead(405, { allow: 'GET, HEAD' }).end() return } const pathname = decode(request.url ?? '/') if (pathname === null) { response.writeHead(400).end() return } // the port is the explorer's alone, so the root is the way in if (pathname === '/') { response.writeHead(302, { location: UI_PATH + '/' }).end() return } const file = this.resolve(pathname) if (file === null) response.writeHead(404).end() else await this.send(file, request, response) } /** * The file a request lands on, or `null` when nothing does. A path that exists is * served as it is; anything else that could be a route falls back to the page, * because the client router — not this server — knows what routes there are. */ private resolve(pathname: string): string | null { if (!pathname.startsWith(UI_PATH)) return null const relative = pathname.slice(UI_PATH.length) if (relative !== '' && !relative.startsWith('/')) return null const file = path.join(this.root, relative) if (file !== this.root && !file.startsWith(this.root + path.sep)) return null if (isFile(file)) return file /* * A missing asset is missing, but a route can look like one: `identity.passkeys` is a * component, not a file with an extension. What this server would have served is what * it knows how to serve, so anything else is a route and falls back to the page — as * does anything ending in a slash, which is no name for a file at all. */ const asset = !relative.endsWith('/') && path.extname(relative) in TYPES return asset ? null : path.join(this.root, 'index.html') } private async send( file: string, request: http.IncomingMessage, response: http.ServerResponse ): Promise { const stats = await fs.promises.stat(file).catch(() => null) if (stats === null) { response .writeHead(503, { 'content-type': 'text/plain' }) .end('The configuration UI is not built. Run `npm run build:ui`.\n') return } response.writeHead(200, { 'content-type': TYPES[path.extname(file)] ?? 'application/octet-stream', 'content-length': stats.size, 'cache-control': caching(path.relative(this.root, file)) }) if (request.method === 'HEAD') response.end() else fs.createReadStream(file).pipe(response) } } function decode(url: string): string | null { try { return decodeURIComponent(url.split('?')[0]) } catch { return null } } function isFile(file: string): boolean { return fs.existsSync(file) && fs.statSync(file).isFile() } /** Where `npm run build:ui` puts the page, from both `source` and `transpiled`. */ const SITE = path.resolve(import.meta.dirname, '..', 'ui', 'dist') /** Assets under this prefix carry their build hash in the name. */ const IMMUTABLE = path.join('_app', 'immutable') const FOREVER = 'public, max-age=31536000, immutable' /** The icons: named without a hash, so they are re-read, but rarely. */ const ICONS = new Set(['favicon.ico', 'favicon-96x96.png', 'apple-touch-icon.png']) const DAY = 'public, max-age=86400' /** * How long what is served may be held. The page is never cached — it names the assets, * and their names carry the build. An icon is named for what it is rather than for its * content, so it is asked about again, but not on every page load. */ function caching(relative: string): string { if (relative.startsWith(IMMUTABLE)) return FOREVER return ICONS.has(relative) ? DAY : 'no-cache' } const TYPES: Record = { '.css': 'text/css; charset=utf-8', '.html': 'text/html; charset=utf-8', '.ico': 'image/x-icon', '.jpg': 'image/jpeg', '.js': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8', '.map': 'application/json; charset=utf-8', '.png': 'image/png', '.svg': 'image/svg+xml', '.txt': 'text/plain; charset=utf-8', '.webmanifest': 'application/manifest+json', '.webp': 'image/webp', '.woff': 'font/woff', '.woff2': 'font/woff2' }