toes/src/server/proxy.ts
2026-02-16 09:34:19 -08:00

114 lines
3.1 KiB
TypeScript

import type { ServerWebSocket } from 'bun'
import { getApp } from '$apps'
const upstreams = new Map<ServerWebSocket<WsData>, WebSocket>()
interface WsData {
port: number
path: string
}
export function extractSubdomain(host: string): string | null {
// Strip port
const hostname = host.replace(/:\d+$/, '')
// *.localhost -> take prefix (e.g. clock.localhost -> clock)
if (hostname.endsWith('.localhost')) {
const sub = hostname.slice(0, -'.localhost'.length)
return sub || null
}
// *.X.local -> take first segment if 3+ parts (e.g. clock.toes.local -> clock)
if (hostname.endsWith('.local')) {
const parts = hostname.split('.')
if (parts.length >= 3) {
return parts[0]!
}
}
return null
}
export async function proxySubdomain(subdomain: string, req: Request): Promise<Response> {
const app = getApp(subdomain)
if (!app || app.state !== 'running' || !app.port) {
return new Response(`App "${subdomain}" not found or not running`, { status: 502 })
}
const url = new URL(req.url)
const target = `http://localhost:${app.port}${url.pathname}${url.search}`
const hasBody = req.method !== 'GET' && req.method !== 'HEAD'
const body = hasBody ? await req.arrayBuffer() : undefined
const headers = new Headers(req.headers)
headers.delete('host')
headers.delete('connection')
headers.delete('keep-alive')
headers.delete('transfer-encoding')
try {
return await fetch(target, {
method: req.method,
headers,
body,
})
} catch (e) {
console.error(`Proxy error for ${subdomain}:`, e)
return new Response(`App "${subdomain}" is not responding`, { status: 502 })
}
}
export function proxyWebSocket(subdomain: string, req: Request, server: any): Response | undefined {
const app = getApp(subdomain)
if (!app || app.state !== 'running' || !app.port) {
return new Response(`App "${subdomain}" not found or not running`, { status: 502 })
}
const url = new URL(req.url)
const path = url.pathname + url.search
const ok = server.upgrade(req, { data: { port: app.port, path } as WsData })
if (ok) return undefined
return new Response('WebSocket upgrade failed', { status: 500 })
}
export const websocket = {
open(ws: ServerWebSocket<WsData>) {
const { port, path } = ws.data
const upstream = new WebSocket(`ws://localhost:${port}${path}`)
upstream.binaryType = 'arraybuffer'
upstreams.set(ws, upstream)
upstream.addEventListener('message', e => {
ws.send(e.data as string | ArrayBuffer)
})
upstream.addEventListener('close', () => {
upstreams.delete(ws)
ws.close()
})
upstream.addEventListener('error', () => {
upstreams.delete(ws)
ws.close()
})
},
message(ws: ServerWebSocket<WsData>, msg: string | ArrayBuffer | Uint8Array) {
const upstream = upstreams.get(ws)
if (!upstream || upstream.readyState !== WebSocket.OPEN) return
upstream.send(msg)
},
close(ws: ServerWebSocket<WsData>) {
const upstream = upstreams.get(ws)
if (upstream) {
upstream.close()
upstreams.delete(ws)
}
},
}