├── .gitignore ├── .editorconfig ├── .eslintrc.json ├── client.js ├── tunnel.js ├── .github └── workflows │ └── test.yml ├── license.md ├── cli ├── server.js └── client.js ├── test.js ├── package.json ├── server.js ├── readme.md └── CODE_OF_CONDUCT.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | Thumbs.db 3 | 4 | .nvm-version 5 | node_modules 6 | npm-debug.log 7 | 8 | /package-lock.json 9 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | root = true 3 | 4 | [*] 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | # Use tabs in JavaScript and JSON. 11 | [**.{js, json}] 12 | indent_style = tab 13 | indent_size = 4 14 | 15 | # Use spaces in YAML. 16 | [**.{yml,yaml}] 17 | indent_style = spaces 18 | indent_size = 2 19 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "eslint:recommended", 3 | "env": { 4 | "es2020": true, 5 | "node": true 6 | }, 7 | "ignorePatterns": [ 8 | "node_modules" 9 | ], 10 | "rules": { 11 | "no-unused-vars": [ 12 | "error", 13 | { 14 | "vars": "all", 15 | "args": "none", 16 | "ignoreRestSiblings": false 17 | } 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /client.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const {createServer} = require('net') 4 | const {tunnelTo} = require('./tunnel') 5 | 6 | const startClient = (tunnel, target, port, opt, cb) => { 7 | if (arguments.length === 4 && 'function' === typeof opt) { 8 | cb = opt 9 | opt = {} 10 | } 11 | const tcpServer = createServer(tunnelTo(tunnel, target, opt)) 12 | 13 | tcpServer.listen(port, cb) 14 | return tcpServer 15 | } 16 | 17 | module.exports = startClient 18 | -------------------------------------------------------------------------------- /tunnel.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const ws = require('websocket-stream') 4 | const pipe = require('pump') 5 | const debug = require('debug')('tcp-over-websockets:client') 6 | 7 | const tunnelTo = (tunnel, target, opt) => (local) => { 8 | const remote = ws(tunnel + (tunnel.slice(-1) === '/' ? '' : '/') + target, opt) 9 | 10 | const onError = (err) => { 11 | if (err) debug(err) 12 | } 13 | pipe(remote, local, onError) 14 | pipe(local, remote, onError) 15 | } 16 | 17 | module.exports = {tunnelTo} 18 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | 3 | on: 4 | push: 5 | branches: 6 | - '*' 7 | pull_request: 8 | branches: 9 | - '*' 10 | 11 | jobs: 12 | test: 13 | runs-on: ubuntu-latest 14 | strategy: 15 | matrix: 16 | node-version: ['14', '16', '18'] 17 | 18 | steps: 19 | - name: checkout 20 | uses: actions/checkout@v2 21 | - name: setup Node v${{ matrix.node-version }} 22 | uses: actions/setup-node@v1 23 | with: 24 | node-version: ${{ matrix.node-version }} 25 | - run: npm install 26 | 27 | - run: npm run lint 28 | - run: npm test 29 | -------------------------------------------------------------------------------- /license.md: -------------------------------------------------------------------------------- 1 | Copyright (c) 2024, Jannis R 2 | 3 | Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. 4 | 5 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 6 | -------------------------------------------------------------------------------- /cli/server.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 'use strict' 3 | 4 | const mri = require('mri') 5 | const pkg = require('../package.json') 6 | 7 | const argv = mri(process.argv.slice(2), { 8 | boolean: ['help', 'h', 'version', 'v'] 9 | }) 10 | 11 | if (argv.help || argv.h) { 12 | process.stdout.write(` 13 | Usage: 14 | tcp-over-websockets-server 15 | Options: 16 | --port -p The port to listen on. Default: 8080 17 | \n`) 18 | process.exit() 19 | } 20 | 21 | if (argv.version || argv.v) { 22 | process.stdout.write(`${pkg.name} v${pkg.version}\n`) 23 | process.exit() 24 | } 25 | 26 | const startServer = require('../server') 27 | 28 | const port = parseInt(argv.port || argv.p || 8080) 29 | 30 | startServer(port, (err) => { 31 | if (err) { 32 | console.error(err) 33 | process.exit(1) 34 | } else console.info(`listening on ${port}`) 35 | }) 36 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const {createServer: createHttpServer, get: httpGet} = require('http') 4 | const {strictEqual} = require('assert') 5 | const startServer = require('./server') 6 | const startClient = require('./client') 7 | 8 | const showError = (err) => { 9 | if (!err) return; 10 | console.error(err) 11 | process.exit(1) 12 | } 13 | 14 | const httpServer = createHttpServer((_, res) => res.end('yay!')) 15 | httpServer.listen(5000, (err) => { 16 | if (err) return showError(err) 17 | 18 | const server = startServer(8080, (err) => { 19 | if (err) return showError(err) 20 | 21 | const headers = { 22 | foo: 'BaR', 23 | hello: 'world', 24 | } 25 | const client = startClient('ws://localhost:8080', 'localhost:5000', 5001, {headers}, (err) => { 26 | if (err) return showError(err) 27 | 28 | httpGet('http://localhost:5001', (res) => { 29 | res.once('data', (data) => { 30 | strictEqual(data.toString('utf-8'), 'yay!') 31 | console.info('works!') 32 | 33 | client.close() 34 | server.httpServer.close() 35 | httpServer.close() 36 | }) 37 | }) 38 | }) 39 | }) 40 | }) 41 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tcp-over-websockets", 3 | "description": "Tunnel TCP through WebSockets.", 4 | "version": "2.2.0", 5 | "main": "server.js", 6 | "bin": { 7 | "tcp-over-websockets": "./cli/client.js", 8 | "tcp-over-websockets-server": "./cli/server.js" 9 | }, 10 | "files": [ 11 | "client.js", 12 | "server.js", 13 | "tunnel.js", 14 | "cli" 15 | ], 16 | "keywords": [ 17 | "tcp", 18 | "tunnel", 19 | "websocket", 20 | "http" 21 | ], 22 | "author": "Jannis R ", 23 | "contributors": [ 24 | "xiaoyun94 " 25 | ], 26 | "homepage": "https://github.com/derhuerst/tcp-over-websockets", 27 | "repository": "derhuerst/tcp-over-websockets", 28 | "bugs": "https://github.com/derhuerst/tcp-over-websockets/issues", 29 | "license": "ISC", 30 | "engines": { 31 | "node": ">=14" 32 | }, 33 | "dependencies": { 34 | "debug": "^4.1.0", 35 | "mri": "^1.1.0", 36 | "pump": "^3.0.0", 37 | "websocket-stream": "^5.1.1" 38 | }, 39 | "scripts": { 40 | "lint": "eslint .", 41 | "start": "node server.js", 42 | "test": "node test.js", 43 | "prepublishOnly": "npm run lint && npm test" 44 | }, 45 | "devDependencies": { 46 | "eslint": "^8.22.0" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const {createConnection} = require('net') 4 | const {createServer: createHttpServer} = require('http') 5 | const url = require('url') 6 | const {createServer: createWsServer} = require('websocket-stream') 7 | const pump = require('pump') 8 | const debug = require('debug')('tcp-over-websockets:server') 9 | 10 | const verifyRequest = (req, res) => { 11 | if (req.upgrade) return 12 | res.statusCode = 405 13 | res.end('connect via WebSocket protocol') 14 | } 15 | 16 | const startServer = (port, cb) => { 17 | const httpServer = createHttpServer(verifyRequest) 18 | 19 | const verifyClient = ({req}, cb) => { 20 | const target = url.parse(req.url).pathname.slice(1) 21 | const [hostname, port] = target.split(':') 22 | req.tunnelPort = +port 23 | req.tunnelHostname = hostname 24 | cb(!isNaN(port) && hostname, 400, 'invalid target') 25 | } 26 | 27 | const wsServer = createWsServer({ 28 | server: httpServer, 29 | verifyClient 30 | }, (remote, req) => { 31 | const target = createConnection(req.tunnelPort, req.tunnelHostname) 32 | target.on('error', console.error) 33 | 34 | const onStreamError = (err) => { 35 | if (err) debug(err) 36 | } 37 | target.once('connect', () => { 38 | pump(remote, target, onStreamError) 39 | pump(target, remote, onStreamError) 40 | }) 41 | }) 42 | 43 | httpServer.listen(port, cb) 44 | return {httpServer, wsServer} 45 | } 46 | 47 | module.exports = startServer 48 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # tcp-over-websockets 2 | 3 | **Tunnel TCP through WebSockets.** Access anything you want, even from a crappy WiFi which only allows HTTPS. 4 | 5 | *Note:* [chisel](https://github.com/jpillora/chisel) is probably the same thing but better. [`@mdslab/wstun`](https://github.com/MDSLab/wstun) is similar. 6 | 7 | [![npm version](https://img.shields.io/npm/v/tcp-over-websockets.svg)](https://www.npmjs.com/package/tcp-over-websockets) 8 | ![ISC-licensed](https://img.shields.io/github/license/derhuerst/tcp-over-websockets.svg) 9 | [![support me via GitHub Sponsors](https://img.shields.io/badge/support%20me-donate-fa7664.svg)](https://github.com/sponsors/derhuerst) 10 | [![chat with me on Twitter](https://img.shields.io/badge/chat%20with%20me-on%20Twitter-1da1f2.svg)](https://twitter.com/derhuerst) 11 | 12 | 13 | ## tunneling client 14 | 15 | Using [`npx`](https://www.npmjs.com/package/npx): 16 | 17 | ```shell 18 | npx tcp-over-websockets wss://example.org github.com:22 8022 19 | ``` 20 | 21 | Or by installing manually: 22 | 23 | ```shell 24 | npm install -g tcp-over-websockets 25 | tcp-over-websockets wss://example.org github.com:22 8022 26 | ``` 27 | 28 | This will expose `github.com:22` on `localhost:8022`, tunneled through a tunneling server at `example.org`. 29 | 30 | Works like `ssh -N -L 8022:github.com:22 user@example.org`, except that it's TCP over WebSockets instead of TCP over SSH. 31 | 32 | 33 | ## tunneling server 34 | 35 | Using [`npx`](https://www.npmjs.com/package/npx): 36 | 37 | ```shell 38 | npx -p tcp-over-websockets tcp-over-websockets-server 39 | ``` 40 | 41 | Or by installing manually: 42 | 43 | ```shell 44 | npm i -g tcp-over-websockets 45 | tcp-over-websockets-server 46 | ``` 47 | 48 | 49 | ## Contributing 50 | 51 | If you **have a question**, **found a bug** or want to **propose a feature**, have a look at [the issues page](https://github.com/derhuerst/tcp-over-websockets/issues). 52 | -------------------------------------------------------------------------------- /cli/client.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 'use strict' 3 | 4 | const mri = require('mri') 5 | const pkg = require('../package.json') 6 | 7 | const argv = mri(process.argv.slice(2), { 8 | boolean: ['help', 'h', 'version', 'v'], 9 | alias : {H: 'header'} 10 | }) 11 | 12 | if (argv.help || argv.h) { 13 | process.stdout.write(` 14 | Usage: 15 | tcp-over-websockets [options] 16 | Arguments: 17 | tunnel-url The WebSocket address of the tunnel server. 18 | tunnelled-target The hostname & port to let the tunnel server connect to. 19 | port-to-listen-on The (local) port to expose the tunnel on. 20 | Options: 21 | -H, --header
Pass custom header(s) to tunnel server 22 | Example: 23 | tcp-over-websockets wss://example.org localhost:22 8022 24 | tcp-over-websockets --header "Cookie:FOOL" wss://example.org localhost:22 8022 25 | \n`) 26 | process.exit(0) 27 | } 28 | if (argv.version || argv.v) { 29 | process.stdout.write(`${pkg.name} v${pkg.version}\n`) 30 | process.exit(0) 31 | } 32 | 33 | const startClient = require('../client') 34 | 35 | const showError = (msg) => { 36 | console.error(msg) 37 | process.exit(1) 38 | } 39 | 40 | const tunnel = argv._[0] 41 | if (!tunnel) showError('missing tunnel argument') 42 | const target = argv._[1] 43 | if (!target) showError('missing target argument') 44 | const port = argv._[2] 45 | if (!port) showError('missing port argument') 46 | 47 | const headers = {} 48 | const headerArgs = Array.isArray(argv.header) ? argv.header : [argv.header] 49 | for (const arg of headerArgs) { 50 | // we follow curl's mechanism here 51 | // https://github.com/curl/curl/blob/d5b0fee39a7898dac42cb4fc64e35f5bc085e766/lib/headers.c#L200-L219 52 | const match = /(?<=\w):\s+(?=.)/.exec(arg); 53 | if (!match) showError(`invalid --header value: '${arg}'`) 54 | const name = arg.slice(0, match.index) 55 | const val = arg.slice(match.index + match[0].length) 56 | headers[name] = val 57 | } 58 | 59 | startClient(tunnel, target, port, {headers}, (err) => { 60 | if (err) showError(err) 61 | else console.info(`tunneling ${target} via ${tunnel} & exposing it on port ${port}`) 62 | }) 63 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at mail@jannisr.de. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | --------------------------------------------------------------------------------