|
| 1 | +import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware'; |
| 2 | +import { createServer } from 'http'; |
| 3 | +import { match } from 'path-to-regexp'; |
| 4 | +import WebSocket, { WebSocketServer } from 'ws'; |
| 5 | +import express from 'express'; |
| 6 | + |
| 7 | +import removeInline from './removeInline'; |
| 8 | + |
| 9 | +import type { Data } from 'ws'; |
| 10 | +import type { IncomingMessage } from 'http'; |
| 11 | +import type { Options } from 'http-proxy-middleware'; |
| 12 | +import type { Socket } from 'net'; |
| 13 | + |
| 14 | +type OnUpgradeHandler = (req: IncomingMessage, socket: Socket, head: Buffer, next: OnUpgradeHandler) => void; |
| 15 | + |
| 16 | +type OnWebSocketMessageHandler = ( |
| 17 | + data: Data, |
| 18 | + socket: WebSocket, |
| 19 | + req: IncomingMessage, |
| 20 | + next: OnWebSocketMessageHandler |
| 21 | +) => void; |
| 22 | + |
| 23 | +type CreateBotProxyInit = { |
| 24 | + onUpgrade?: OnUpgradeHandler; |
| 25 | + onWebSocketReceiveMessage?: OnWebSocketMessageHandler; |
| 26 | + onWebSocketSendMessage?: OnWebSocketMessageHandler; |
| 27 | + streamingBotURL?: string; |
| 28 | +}; |
| 29 | + |
| 30 | +type CreateBotProxyReturnValue = { |
| 31 | + cleanUp: () => void; |
| 32 | + closeAllWebSocketConnections: () => void; |
| 33 | + directLineStreamingURL: string; |
| 34 | + directLineURL: string; |
| 35 | +}; |
| 36 | + |
| 37 | +const matchDirectLineStreamingProtocol = match('/.bot/', { decode: decodeURIComponent, end: false }); |
| 38 | + |
| 39 | +export default function createBotProxy(init?: CreateBotProxyInit): Promise<CreateBotProxyReturnValue> { |
| 40 | + const onUpgrade = init?.onUpgrade || ((req, socket, head, next) => next(req, socket, head, () => {})); |
| 41 | + const onWebSocketReceiveMessage = |
| 42 | + init?.onWebSocketReceiveMessage || ((data, socket, req, next) => next(data, socket, req, () => {})); |
| 43 | + const onWebSocketSendMessage = |
| 44 | + init?.onWebSocketSendMessage || ((data, socket, req, next) => next(data, socket, req, () => {})); |
| 45 | + const streamingBotURL = init?.streamingBotURL; |
| 46 | + |
| 47 | + return new Promise<CreateBotProxyReturnValue>((resolve, reject) => { |
| 48 | + try { |
| 49 | + const activeSockets: Socket[] = []; |
| 50 | + const app = express(); |
| 51 | + |
| 52 | + streamingBotURL && |
| 53 | + app.use('/.bot/', createProxyMiddleware({ changeOrigin: true, logLevel: 'silent', target: streamingBotURL })); |
| 54 | + |
| 55 | + const onProxyRes: Options['onProxyRes'] = responseInterceptor( |
| 56 | + async (responseBuffer, proxyRes: IncomingMessage) => { |
| 57 | + const { |
| 58 | + socket: { localAddress, localPort }, |
| 59 | + statusCode |
| 60 | + } = proxyRes; |
| 61 | + |
| 62 | + if (statusCode && statusCode >= 200 && statusCode < 300) { |
| 63 | + try { |
| 64 | + const json = JSON.parse(responseBuffer.toString('utf8')); |
| 65 | + |
| 66 | + if (json.streamUrl) { |
| 67 | + return JSON.stringify({ |
| 68 | + ...json, |
| 69 | + streamUrl: json.streamUrl.replace( |
| 70 | + /^wss:\/\/directline.botframework.com\/v3\/directline\//, |
| 71 | + `ws://${localAddress}:${localPort}/v3/directline/` |
| 72 | + ) |
| 73 | + }); |
| 74 | + } |
| 75 | + } catch (error) { |
| 76 | + // Returns original response if it is not a JSON. |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + return responseBuffer; |
| 81 | + |
| 82 | + // There is a typing bug in `http-proxy-middleware`. |
| 83 | + // The return type of `responseIntercept` does not match `onProxyRes`. |
| 84 | + } |
| 85 | + ); |
| 86 | + |
| 87 | + app.use( |
| 88 | + '/v3/directline', |
| 89 | + createProxyMiddleware({ |
| 90 | + changeOrigin: true, |
| 91 | + logLevel: 'silent', |
| 92 | + onProxyRes, |
| 93 | + selfHandleResponse: true, |
| 94 | + target: 'https://directline.botframework.com/' |
| 95 | + }) |
| 96 | + ); |
| 97 | + |
| 98 | + const webSocketProxy = new WebSocketServer({ noServer: true }); |
| 99 | + |
| 100 | + webSocketProxy.on('connection', (socket: WebSocket, proxySocket: WebSocket, req: IncomingMessage) => { |
| 101 | + socket.addEventListener('message', ({ data }) => |
| 102 | + onWebSocketSendMessage(data, proxySocket, req, (data, proxySocket) => proxySocket.send(data)) |
| 103 | + ); |
| 104 | + |
| 105 | + proxySocket.addEventListener('message', ({ data }) => |
| 106 | + onWebSocketReceiveMessage(data, socket, req, (data, socket) => socket.send(data)) |
| 107 | + ); |
| 108 | + }); |
| 109 | + |
| 110 | + const server = createServer(app); |
| 111 | + |
| 112 | + server.on('error', reject); |
| 113 | + |
| 114 | + server.on('upgrade', (req: IncomingMessage, socket: Socket, head: Buffer) => |
| 115 | + onUpgrade(req, socket, head, (req, socket, head) => { |
| 116 | + activeSockets.push(socket); |
| 117 | + |
| 118 | + socket.once('close', () => removeInline(activeSockets, socket)); |
| 119 | + |
| 120 | + const requestURL = req.url || ''; |
| 121 | + |
| 122 | + const isDirectLineStreaming = !!matchDirectLineStreamingProtocol(requestURL); |
| 123 | + |
| 124 | + if (isDirectLineStreaming && !streamingBotURL) { |
| 125 | + console.warn('Cannot proxy /.bot/ requests without specifying "streamingBotURL".'); |
| 126 | + |
| 127 | + return socket.end(); |
| 128 | + } |
| 129 | + |
| 130 | + const targetURL = new URL( |
| 131 | + requestURL, |
| 132 | + isDirectLineStreaming ? streamingBotURL : 'wss://directline.botframework.com/' |
| 133 | + ); |
| 134 | + |
| 135 | + // "streamingBotURL" could be "https:" instead of "wss:". |
| 136 | + targetURL.protocol = 'wss:'; |
| 137 | + |
| 138 | + const proxySocket = new WebSocket(targetURL); |
| 139 | + |
| 140 | + proxySocket.addEventListener('close', () => socket.end()); |
| 141 | + proxySocket.addEventListener('open', () => |
| 142 | + webSocketProxy.handleUpgrade(req, socket, head, ws => |
| 143 | + webSocketProxy.emit('connection', ws, proxySocket, req) |
| 144 | + ) |
| 145 | + ); |
| 146 | + |
| 147 | + socket.once('close', () => proxySocket.close()); |
| 148 | + }) |
| 149 | + ); |
| 150 | + |
| 151 | + server.listen(0, '127.0.0.1', () => { |
| 152 | + const address = server.address(); |
| 153 | + |
| 154 | + if (!address) { |
| 155 | + server.close(); |
| 156 | + |
| 157 | + return reject(new Error('Cannot get address of proxy server.')); |
| 158 | + } |
| 159 | + |
| 160 | + const url = new URL(`http://${typeof address === 'string' ? address : `${address.address}:${address.port}`}`); |
| 161 | + |
| 162 | + const closeAllWebSocketConnections = () => { |
| 163 | + activeSockets.map(socket => socket.end()); |
| 164 | + activeSockets.splice(0); |
| 165 | + }; |
| 166 | + |
| 167 | + resolve({ |
| 168 | + cleanUp: () => { |
| 169 | + server.close(); |
| 170 | + |
| 171 | + // `closeAllConnections` is introduced in Node.js 18.2.0. |
| 172 | + server.closeAllConnections?.(); |
| 173 | + |
| 174 | + // Calling close() and closeAllConnections() will not close all Web Socket connections. |
| 175 | + closeAllWebSocketConnections(); |
| 176 | + }, |
| 177 | + closeAllWebSocketConnections, |
| 178 | + directLineStreamingURL: new URL('/.bot/v3/directline', url).href, |
| 179 | + directLineURL: new URL('/v3/directline', url).href |
| 180 | + }); |
| 181 | + }); |
| 182 | + } catch (error) { |
| 183 | + reject(error); |
| 184 | + } |
| 185 | + }); |
| 186 | +} |
0 commit comments