ln-ws-proxy

websockets to lightning proxy
git clone git://jb55.com/ln-ws-proxy
Log | Files | Refs | README

index.js (1306B)


      1 
      2 
      3 const WebSocket = require('ws')
      4 const net = require('net')
      5 
      6 const {WebSocketServer} = WebSocket
      7 
      8 function ln_ws_proxy_server(opts={}) {
      9 	opts.port = opts.port || process.env.PORT || 8080
     10 
     11 	const server = new WebSocketServer(opts)
     12 
     13 	server.on('connection', handle_connection)
     14 
     15 	return server
     16 }
     17 
     18 function handle_open(ws, req) {
     19 	//console.log("open", req)
     20 	console.log("open")
     21 }
     22 
     23 function parse_ip(str)
     24 {
     25 	const parts = str.split(":")
     26 	return {host: parts[0], port: parts[1] || 9735}
     27 }
     28 
     29 async function handle_connection(ws, req) {
     30 	const url = new URL(`wss://${req.headers.host}${req.url}`)
     31 	const dest = url.pathname.substring(1)
     32 	if (!dest) {
     33 		ws.close()
     34 		return
     35 	}
     36 
     37 	const {host, port} = parse_ip(dest)
     38 	console.log("serving", host, port)
     39 	const is_resolved = false
     40 	let socket = null
     41 
     42 	const connected = new Promise((resolve, reject) => {
     43 		const conn = net.createConnection(port, host, () => {
     44 			socket = conn
     45 			resolve(conn)
     46 		})
     47 	});
     48 
     49 	let messages = []
     50 	ws.on('message', async (msg) => {
     51 		if (socket) {
     52 			socket.write(msg)
     53 			return 
     54 		}
     55 
     56 		messages.push(msg)
     57 	})
     58 
     59 	// queue up messages until we're connected
     60 	socket = await connected
     61 	socket.on('data', (d) => ws.send(d))
     62 
     63 	for (const message of messages) {
     64 		socket.write(message)
     65 	}
     66 	messages = null
     67 }
     68 
     69 module.exports = ln_ws_proxy_server