ln-ws-proxy

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

commit 9820d73a19adeb5c7bb61758a49ce88949e65309
Author: William Casarin <jb55@jb55.com>
Date:   Fri, 15 Jul 2022 18:12:25 -0700

initial commit

Signed-off-by: William Casarin <jb55@jb55.com>

Diffstat:
A.gitignore | 5+++++
AREADME.md | 10++++++++++
Aindex.js | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aln-ws-proxy | 5+++++
Apackage.json | 18++++++++++++++++++
5 files changed, 107 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1,5 @@ +.direnv/ +.envrc +node_modules/ +package-lock.json +shell.nix diff --git a/README.md b/README.md @@ -0,0 +1,10 @@ + +# ln-ws-proxy + +A websockets to lightning proxy + +## Usage + +PORT=8085 ./ln-ws-proxy + +requests to `ws://127.0.0.1/24.84.152.187` will be proxied to `24.84.152.187:9735` over a real (non-websocket) connection diff --git a/index.js b/index.js @@ -0,0 +1,69 @@ + + +const WebSocket = require('ws') +const net = require('net') + +const {WebSocketServer} = WebSocket + +function ln_ws_proxy_server(opts={}) { + opts.port = opts.port || process.env.PORT || 8080 + + const server = new WebSocketServer(opts) + + server.on('connection', handle_connection) + + return server +} + +function handle_open(ws, req) { + //console.log("open", req) + console.log("open") +} + +function parse_ip(str) +{ + const parts = str.split(":") + return {host: parts[0], port: parts[1] || 9735} +} + +async function handle_connection(ws, req) { + const url = new URL(`wss://${req.headers.host}${req.url}`) + const dest = url.pathname.substring(1) + if (!dest) { + ws.close() + return + } + + const {host, port} = parse_ip(dest) + console.log("serving", host, port) + const is_resolved = false + let socket = null + + const connected = new Promise((resolve, reject) => { + const conn = net.createConnection(port, host, () => { + socket = conn + resolve(conn) + }) + }); + + let messages = [] + ws.on('message', async (msg) => { + if (socket) { + socket.write(msg) + return + } + + messages.push(msg) + }) + + // queue up messages until we're connected + socket = await connected + socket.on('data', (d) => ws.send(d)) + + for (const message of messages) { + socket.write(message) + } + messages = null +} + +module.exports = ln_ws_proxy_server diff --git a/ln-ws-proxy b/ln-ws-proxy @@ -0,0 +1,5 @@ +#!/usr/bin/env node + +const make_server = require('./') + +const server = make_server() diff --git a/package.json b/package.json @@ -0,0 +1,18 @@ +{ + "name": "ln-ws-proxy", + "description": "ln-ws-proxy", + "version": "0.1.0", + "repository": { + "url": "https://github.com/jb55/ln-ws-proxy" + }, + "main": "index.js", + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": { + "ws": "^8.8.1" + }, + "devDependencies": { + "tap": "~0.2.5" + } +}