diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..964f0c5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +node_modules +lib +test/testfile* diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..abb0771 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "8" + - "10" + - "11" + - "12" \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f32852c --- /dev/null +++ b/LICENSE @@ -0,0 +1,11 @@ +Copyright 2017 Johan Nordberg + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md deleted file mode 100644 index 8fb6c91..0000000 --- a/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -(The MIT License) - -Copyright (c) 2011 Einar Otto Stangvik - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the 'Software'), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..7b10cd4 --- /dev/null +++ b/Makefile @@ -0,0 +1,37 @@ + +SHELL := /bin/bash +PATH := ./node_modules/.bin:$(PATH) + +SRC_FILES := $(shell find src -name '*.ts') + +.PHONY: all +all: lib + +.PHONY: test +test: node_modules + tslint -p tsconfig.json -c tslint.json && \ + ./test/cli.sh + +.PHONY: lint +lint: node_modules + tslint -p tsconfig.json -c tslint.json -t stylish --fix + +lib: $(SRC_FILES) node_modules + tsc -p tsconfig.json && \ + sed -i "" "1s/ts-node/node/" lib/cli.js && \ + rm lib/cli.d.ts && \ + VERSION="$$(node -p 'require("./package.json").version')"; \ + echo "exports.default = '$${VERSION}';" > lib/version.js && \ + touch lib + +node_modules: + npm ci && \ + touch node_modules + +.PHONY: clean +clean: + rm -rf lib/ + +.PHONY: distclean +distclean: clean + rm -rf node_modules/ diff --git a/README.md b/README.md index 5b87ead..62ae280 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,141 @@ -# wscat -WebSocket cat. +wscat2 [![Build Status](https://travis-ci.org/jnordberg/wscat.svg?branch=master)](https://travis-ci.org/jnordberg/wscat) +====== -## Installation +Unix-style WebSocket cat (or netcat for websockets). -This module needs to be installed globally so use the `-g` flag when installing: + +Installation +------------ + +``` +npm install -g wscat2 +``` + + +Usage +----- + +``` +$ wscat -h +usage: wscat [-h] [-v] [-l PORT] [-b] [-H HEADER] [-n] [-k] [-d] [-s SUBP] [address] + +Positional arguments: + address + +Optional arguments: + -h, --help Show this help message and exit. + -v, --version Show program's version number and exit. + -l PORT, --listen PORT + Start a websocket server on PORT. + -b, --binary Use binary WebSockets. + -H HEADER, --header HEADER + Specify a custom HTTP request header. May be given + multiple times. + -n, --no-check Do not check for unauthorized certificates. + -k, --keep-open Do not close the socket after EOF. + -d, --deflate Use per-message deflate. + -s SUBP, --subprotocol SUBP + WebSocket subprotocol +``` + + +Examples +-------- + +If you ever used `nc`, `wscat` works pretty much the same. + +### Connect to a server + +``` +$ wscat echo.websocket.org +Hello +Hello +Who's there? +Who's there? +^D + +``` + +### Chat + +Server: + +``` +$ wscat -l 12345 +Hi there! +Hi! +It's nice to speak to someone who just dosn't repeat everything I say back at me. +Yeah! Isn't it?! +Sorry, gotta run... +^D + +``` + +Client: + +``` +$ wscat localhost:12345 +Hi there! +Hi! +It's nice to speak to someone who just dosn't repeat everything I say back at me. +Yeah! Isn't it?! +Sorry, gotta run... +``` + +### Transfer a file + +Server: + +``` +$ wscat -b -l 12345 < ~/Desktop/mycat.jpg +``` + +Client: ``` -npm install -g wscat +$ wscat -b localhost:12345 > igotacat.jpg ``` -## Usage +Note that you can have the client send the file as well, after the connection has been setup `wscat` does not differentiate between server/client. + +### Get your bitcoin on ``` -$ wscat -c ws://echo.websocket.org -connected (press CTRL+C to quit) -> hi there -< hi there -> are you a happy parrot? -< are you a happy parrot? +$ echo '{"op":"unconfirmed_sub"}' | wscat -k wss://ws.blockchain.info/inv ``` -## License +The `-k` option is used to keep the socket open after the command has been sent, allowing us to read the continuous stream of Bitcoin transactions. -MIT + +Developing +---------- + +This node.js program is written in TypeScript and has a compile step that you can run with `make lib`. For developing it is convenient to install the `ts-node` and `typescript` modules globally (`npm i -g ..`), this will allow you to directly execute the programs entry-point: `./src/cli.ts`. + +Use `make test` to run the tests and lint check and `make lint` to run the linter in formatter mode. + + +License +------- + +[BSD 3-Clause](https://tldrlegal.com/license/bsd-3-clause-license-(revised)) + +--- + +``` + + /\_/\ /\_/\ + / 0 0 \ / o o \ + ====v==== ====C==== __ __ + \ W / \ V / _( )_( )_ + | | _ | | .-=(_ WEB _) + / ___ \ / / ___ \ / (__ __) + / / \ \ | / / \ \ | (__) + (((-----)))-' (((-----)))-' + / / + ( ___ ___ / + \__.=|___|E 3__|=.__/ + / ^ + +``` diff --git a/bin/wscat b/bin/wscat deleted file mode 100755 index 79eb17d..0000000 --- a/bin/wscat +++ /dev/null @@ -1,227 +0,0 @@ -#!/usr/bin/env node - -/*! - * ws: a node.js websocket client - * Copyright(c) 2011 Einar Otto Stangvik - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var program = require('commander') - , readline = require('readline') - , events = require('events') - , WebSocket = require('ws') - , util = require('util') - , fs = require('fs'); - -/** - * InputReader - processes console input. - */ -function Console() { - if (!(this instanceof Console)) return new Console(); - - this.stdin = process.stdin; - this.stdout = process.stdout; - - this.readlineInterface = readline.createInterface(this.stdin, this.stdout); - - var self = this; - - this.readlineInterface.on('line', function line(data) { - self.emit('line', data); - }).on('close', function close() { - self.emit('close'); - }); - - this._resetInput = function() { - self.clear(); - }; -} - -util.inherits(Console, events.EventEmitter); - -Console.Colors = { - Red: '\033[31m', - Green: '\033[32m', - Yellow: '\033[33m', - Blue: '\033[34m', - Default: '\033[39m' -}; - -Console.prototype.prompt = function prompt() { - this.readlineInterface.prompt(); -}; - -Console.prototype.print = function print(msg, color) { - this.clear(); - color = color || Console.Colors.Default; - this.stdout.write(color + msg + Console.Colors.Default + '\n'); - this.prompt(); -}; - -Console.prototype.clear = function clear() { - this.stdout.write('\033[2K\033[E'); -}; - -Console.prototype.pause = function pausing() { - this.stdin.on('keypress', this._resetInput); -}; - -Console.prototype.resume = function resume() { - this.stdin.removeListener('keypress', this._resetInput); -}; - -function appender(xs) { - xs = xs || []; - - return function (x) { - xs.push(x); - return xs; - }; -} - -function into(obj, kvals) { - kvals.forEach(function (kv) { - obj[kv[0]] = kv[1]; - }); - - return obj; -} - -function splitOnce(sep, str) { // sep can be either String or RegExp - var tokens = str.split(sep); - return [tokens[0], str.replace(sep, '').substr(tokens[0].length)]; -} - -/** - * The actual application - */ -var version = require('../package.json').version; - -program - .version(version) - .usage('[options] (--listen | --connect )') - .option('-l, --listen ', 'listen on port') - .option('-c, --connect ', 'connect to a websocket server') - .option('-p, --protocol ', 'optional protocol version') - .option('-o, --origin ', 'optional origin') - .option('--host ', 'optional host') - .option('-s, --subprotocol ', 'optional subprotocol') - .option('-n, --no-check', 'Do not check for unauthorized certificates') - .option('-H, --header ', 'Set an HTTP header. Repeat to set multiple. (--connect only)', appender(), []) - .option('--auth ', 'Add basic HTTP authentication header. (--connect only)') - .parse(process.argv); - -if (program.listen && program.connect) { - console.error('\033[33merror: use either --listen or --connect\033[39m'); - process.exit(-1); -} else if (program.listen) { - var wsConsole = new Console(); - wsConsole.pause(); - - var options = {}; - - if (program.protocol) options.protocolVersion = program.protocol; - if (program.origin) options.origin = program.origin; - if (program.subprotocol) options.protocol = program.subprotocol; - if (!program.check) options.rejectUnauthorized = program.check; - - var ws = null; - var wss = new WebSocket.Server({ port: program.listen }, function listening() { - wsConsole.print('listening on port ' + program.listen + ' (press CTRL+C to quit)', Console.Colors.Green); - wsConsole.clear(); - }); - - wsConsole.on('close', function close() { - try { ws.close(); } - catch (e) {} - - process.exit(0); - }); - - wsConsole.on('line', function line(data) { - if (ws) { - ws.send(data, { mask: false }); - wsConsole.prompt(); - } - }); - - wss.on('connection', function(newClient) { - if (ws) return newClient.terminate(); - - ws = newClient; - wsConsole.resume(); - wsConsole.prompt(); - wsConsole.print('client connected', Console.Colors.Green); - - ws.on('close', function close() { - wsConsole.print('disconnected', Console.Colors.Green); - wsConsole.clear(); - wsConsole.pause(); - ws = null; - }).on('error', function error(code, description) { - wsConsole.print('error: ' + code + (description ? ' ' + description : ''), Console.Colors.Yellow); - }).on('message', function message(data, flags) { - wsConsole.print('< ' + data, Console.Colors.Blue); - }); - }).on('error', function servererrror(error) { - wsConsole.print('error: ' + error.toString(), Console.Colors.Yellow); - process.exit(-1); - }); -} else if (program.connect) { - var wsConsole = new Console(); - var options = {}; - - if (program.protocol) options.protocolVersion = program.protocol; - if (program.origin) options.origin = program.origin; - if (program.subprotocol) options.protocol = program.subprotocol; - if (program.host) options.host = program.host; - if (!program.check) options.rejectUnauthorized = program.check; - - var headers = into({}, (program.header || []).map(function split(s) { - return splitOnce(':', s); - })); - - if (program.auth) { - headers.Authorization = 'Basic '+ new Buffer(program.auth).toString('base64'); - } - - var connectUrl = program.connect; - if (!connectUrl.match(/\w+:\/\/.*$/i)) { - connectUrl = 'ws://' + connectUrl; - } - - options.headers = headers; - var ws = new WebSocket(connectUrl, options); - - ws.on('open', function open() { - wsConsole.print('connected (press CTRL+C to quit)', Console.Colors.Green); - wsConsole.on('line', function line(data) { - ws.send(data, { mask: true }); - wsConsole.prompt(); - }); - }).on('close', function close() { - wsConsole.print('disconnected', Console.Colors.Green); - wsConsole.clear(); - process.exit(); - }).on('error', function error(code, description) { - wsConsole.print('error: ' + code + (description ? ' ' + description : ''), Console.Colors.Yellow); - process.exit(-1); - }).on('message', function message(data, flags) { - wsConsole.print('< ' + data, Console.Colors.Blue); - }); - - wsConsole.on('close', function close() { - if (!ws) return; - - try { ws.close(); } - catch(e) {} - - process.exit(); - }); -} else { - program.help(); -} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..761dba1 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,411 @@ +{ + "name": "wscat2", + "version": "2.4.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@babel/code-frame": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz", + "integrity": "sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==", + "dev": true, + "requires": { + "@babel/highlight": "^7.0.0" + } + }, + "@babel/highlight": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0.tgz", + "integrity": "sha512-UFMC4ZeFC48Tpvj7C8UgLvtkaUuovQX+5xNWrsIoMG8o2z+XFKjKaN9iVmS84dPwVN00W4wPmqvYoZF3EGAsfw==", + "dev": true, + "requires": { + "chalk": "^2.0.0", + "esutils": "^2.0.2", + "js-tokens": "^4.0.0" + } + }, + "@types/argparse": { + "version": "1.0.36", + "resolved": "https://registry.npmjs.org/@types/argparse/-/argparse-1.0.36.tgz", + "integrity": "sha512-3+i1qzPwyNjbJeiZuJQuETdAe7kWsbI+Vrpj8kbdqAEsXaBDxHPEPg6tXGeDEP0DDPrOnvyFJjm6XNOoK6685w==", + "dev": true + }, + "@types/events": { + "version": "1.2.0", + "resolved": "http://registry.npmjs.org/@types/events/-/events-1.2.0.tgz", + "integrity": "sha512-KEIlhXnIutzKwRbQkGWb/I4HFqBuUykAdHgDED6xqwXJfONCjF5VoE0cXEiurh3XauygxzeDzgtXUqvLkxFzzA==", + "dev": true + }, + "@types/node": { + "version": "10.12.9", + "resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.9.tgz", + "integrity": "sha512-eajkMXG812/w3w4a1OcBlaTwsFPO5F7fJ/amy+tieQxEMWBlbV1JGSjkFM+zkHNf81Cad+dfIRA+IBkvmvdAeA==", + "dev": true + }, + "@types/ws": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-6.0.1.tgz", + "integrity": "sha512-EzH8k1gyZ4xih/MaZTXwT2xOkPiIMSrhQ9b8wrlX88L0T02eYsddatQlwVFlEPyEqV0ChpdpNnE51QPH6NVT4Q==", + "dev": true, + "requires": { + "@types/events": "*", + "@types/node": "*" + } + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "arg": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.0.tgz", + "integrity": "sha512-ZWc51jO3qegGkVh8Hwpv636EkbesNV5ZNQPCtRa+0qytRYPEs9IYT9qITY9buezqUH5uqyzlWLcufrzU2rffdg==", + "dev": true + }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "requires": { + "sprintf-js": "~1.0.2" + } + }, + "async-limiter": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz", + "integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==" + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "buffer-from": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", + "dev": true + }, + "builtin-modules": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz", + "integrity": "sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8=", + "dev": true + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "dev": true + }, + "commander": { + "version": "2.20.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "diff": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", + "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==", + "dev": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "dev": true + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + }, + "js-yaml": { + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", + "dev": true, + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, + "make-error": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.5.tgz", + "integrity": "sha512-c3sIjNUow0+8swNwVpqoH4YCShKNFkMaw6oH1mNS2haDZQqkeZFlHS3dhoeEbKKmJB4vXpJucU6oH75aDYeE9g==", + "dev": true + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "dev": true + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "http://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "dev": true, + "requires": { + "minimist": "0.0.8" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "http://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "path-parse": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", + "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==", + "dev": true + }, + "resolve": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.1.tgz", + "integrity": "sha512-vIpgF6wfuJOZI7KKKSP+HmiKggadPQAdsp5HiC1mvqnfp0gF1vdwgBWZIdrVft9pgqoMFQN+R7BSWZiBxx+BBw==", + "dev": true, + "requires": { + "path-parse": "^1.0.6" + } + }, + "semver": { + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz", + "integrity": "sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + }, + "source-map-support": { + "version": "0.5.12", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.12.tgz", + "integrity": "sha512-4h2Pbvyy15EE02G+JOZpUCmqWJuqrs+sEkzewTm++BPi7Hvn/HwcqLAcNxYAyI0x13CpPPn+kMjl+hplXMHITQ==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=" + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "ts-node": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-8.3.0.tgz", + "integrity": "sha512-dyNS/RqyVTDcmNM4NIBAeDMpsAdaQ+ojdf0GOLqE6nwJOgzEkdRNzJywhDfwnuvB10oa6NLVG1rUJQCpRN7qoQ==", + "dev": true, + "requires": { + "arg": "^4.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "source-map-support": "^0.5.6", + "yn": "^3.0.0" + } + }, + "tslib": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.10.0.tgz", + "integrity": "sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ==", + "dev": true + }, + "tslint": { + "version": "5.18.0", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.18.0.tgz", + "integrity": "sha512-Q3kXkuDEijQ37nXZZLKErssQVnwCV/+23gFEMROi8IlbaBG6tXqLPQJ5Wjcyt/yHPKBC+hD5SzuGaMora+ZS6w==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "builtin-modules": "^1.1.1", + "chalk": "^2.3.0", + "commander": "^2.12.1", + "diff": "^3.2.0", + "glob": "^7.1.1", + "js-yaml": "^3.13.1", + "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", + "resolve": "^1.3.2", + "semver": "^5.3.0", + "tslib": "^1.8.0", + "tsutils": "^2.29.0" + }, + "dependencies": { + "diff": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz", + "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==", + "dev": true + } + } + }, + "tsutils": { + "version": "2.29.0", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-2.29.0.tgz", + "integrity": "sha512-g5JVHCIJwzfISaXpXE1qvNalca5Jwob6FjI4AoPlqMusJ6ftFE7IkkFoMhVLRgK+4Kx3gkzb8UZK5t5yTTvEmA==", + "dev": true, + "requires": { + "tslib": "^1.8.1" + } + }, + "typescript": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.5.2.tgz", + "integrity": "sha512-7KxJovlYhTX5RaRbUdkAXN1KUZ8PwWlTzQdHV6xNqvuFOs7+WBo10TQUqT19Q/Jz2hk5v9TQDIhyLhhJY4p5AA==", + "dev": true + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "ws": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.0.1.tgz", + "integrity": "sha512-ILHfMbuqLJvnSgYXLgy4kMntroJpe8hT41dOVWM8bxRuw6TK4mgMp9VJUNsZTEc5Bh+Mbs0DJT4M0N+wBG9l9A==", + "requires": { + "async-limiter": "^1.0.0" + } + }, + "yn": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.0.tgz", + "integrity": "sha512-kKfnnYkbTfrAdd0xICNFw7Atm8nKpLcLv9AZGEt+kczL/WQVai4e2V6ZN8U/O+iI6WrNuJjNNOyu4zfhl9D3Hg==", + "dev": true + } + } +} diff --git a/package.json b/package.json index 8946fb5..04452f0 100644 --- a/package.json +++ b/package.json @@ -1,28 +1,37 @@ { - "name": "wscat", - "version": "1.0.0", - "description": "WebSocket cat", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + "name": "wscat2", + "version": "2.4.0", + "description": "Unix-style WebSocket cat", + "author": "Johan Nordberg", + "license": "BSD-3-Clause", + "index": "lib/wscat.js", + "bin": { + "wscat": "lib/cli.js" }, + "files": [ + "lib/*" + ], "repository": { "type": "git", - "url": "https://github.com/websockets/wscat" + "url": "https://github.com/jnordberg/wscat" + }, + "scripts": { + "prepublishOnly": "make test && make lib", + "test": "make test" }, "keywords": [ - "wscat", "websocket", "cat" ], - "author": "Arnout Kazemier, Einar Otto Stangvik", - "license": "MIT", "dependencies": { - "commander": "2.5.x", - "tinycolor": "0.0.x", - "ws": "0.4.x" + "argparse": "^1.0.9", + "ws": "^7.0.1" }, - "bin": { - "wscat": "./bin/wscat" + "devDependencies": { + "@types/argparse": "^1.0.36", + "@types/ws": "^6.0.1", + "ts-node": "^8.3.0", + "tslint": "^5.18.0", + "typescript": "^3.5.2" } } diff --git a/src/cli.ts b/src/cli.ts new file mode 100755 index 0000000..6d7ea53 --- /dev/null +++ b/src/cli.ts @@ -0,0 +1,139 @@ +#!/usr/bin/env ts-node + +import {ArgumentParser} from 'argparse' +import version from './version' +import * as wscat from './wscat' + +interface ICLIOptions { + address?: string + binary: boolean + reportClose: boolean + sendResize: string + useRaw: boolean + deflate: boolean + keepOpen: boolean + listen?: number + noCheck: boolean + subProto?: string + header: string[] +} + +const parser = new ArgumentParser({version, addHelp: true}) + +parser.addArgument(['-l', '--listen'], { + help: 'Start a websocket server on PORT.', + metavar: 'PORT', + type: Number, +}) + +parser.addArgument(['-b', '--binary'], { + action: 'storeTrue', + defaultValue: false, + help: 'Use binary WebSockets.', +}) + +parser.addArgument(['-c', '--report-close'], { + action: 'storeTrue', + defaultValue: false, + dest: 'reportClose', + help: 'Write WebSocket $close:$reason to STDERR on close.', +}) + +parser.addArgument(['-R', '--send-resize'], { + dest: 'sendResize', + help: 'Send text frame when client terminal resizes, using template string containing ${columns} and ${rows}.', + metavar: 'SENDRESIZE', + type: String, +}) + +parser.addArgument(['-r', '--raw'], { + action: 'storeTrue', + defaultValue: false, + dest: 'useRaw', + help: 'Use rawmode stdin.', +}) + +parser.addArgument(['-H', '--header'], { + action: 'append', + help: 'Specify a custom HTTP request header. May be given multiple times.', +}) + +parser.addArgument(['-n', '--no-check'], { + action: 'storeTrue', + defaultValue: false, + dest: 'noCheck', + help: 'Do not check for unauthorized certificates.', +}) + +parser.addArgument(['-k', '--keep-open'], { + action: 'storeTrue', + defaultValue: false, + dest: 'keepOpen', + help: 'Do not close the socket after EOF.', +}) + +parser.addArgument(['-d', '--deflate'], { + action: 'storeTrue', + defaultValue: false, + help: 'Use per-message deflate.', +}) + +parser.addArgument(['-s', '--subprotocol'], { + dest: 'subProto', + help: 'WebSocket subprotocol', + metavar: 'SUBP', + type: String, +}) + +parser.addArgument(['address'], { + nargs: '?', + type: String, +}) + +const args = parser.parseArgs() as ICLIOptions + +const headers: any = {} +if (args.header) { + args.header.forEach( (txt) => { + const match = txt.match(/(.+?)\s*:\s*(.+)/) + + if (match) { + headers[ match[1] ] = match[2] + } + } ) +} + +const options: any = { + binary: args.binary, + headers, + inputStream: process.stdin, + keepOpen: args.keepOpen, + outputStream: process.stdout, + perMessageDeflate: args.deflate, + protocol: args.subProto, + rejectUnauthorized: !args.noCheck, + reportClose: args.reportClose, + sendResize: args.sendResize, + useRaw: args.useRaw, +} + +if (args.address) { + if (args.listen) { + throw new Error('Can not use --listen option in conjunction with address') + } + if (!hasProtocol(args.address)) { + args.address = `ws://${ args.address }` + } + options.address = args.address + wscat.connect(options) +} else if (args.listen) { + options.port = args.listen + wscat.listen(options) +} else { + parser.printHelp() +} + +function hasProtocol(url: string): boolean { + const pattern = /^[a-z]+:\/\//i + return pattern.test(url) +} diff --git a/src/stream.ts b/src/stream.ts new file mode 100644 index 0000000..202fbcb --- /dev/null +++ b/src/stream.ts @@ -0,0 +1,37 @@ +import {Duplex} from 'stream' +import * as WebSocket from 'ws' + +export interface IWebSocketStreamOptions { + binary: boolean +} + +export class WebSocketStream extends Duplex { + + public hasWritten: boolean = false + + constructor(private socket: WebSocket, readonly options: IWebSocketStreamOptions) { + super({ + decodeStrings: !options.binary, + encoding: options.binary ? undefined : 'utf-8', + }) + socket.on('message', this.messageHandler) + socket.on('error', (error: Error) => { + this.emit('error', error) + }) + socket.on('close', (code, reason) => { + this.push(null) + this.emit('close', code, reason) + }) + } + + public _write(chunk: any, encoding: string, callback: (error?: Error) => void) { + this.hasWritten = true + this.socket.send(chunk, this.options, callback) + } + + public _read(size: number) {} + + private messageHandler = (data: any, flags: {binary: boolean}) => { + this.push(data) + } +} diff --git a/src/version.ts b/src/version.ts new file mode 100644 index 0000000..10b8c37 --- /dev/null +++ b/src/version.ts @@ -0,0 +1,3 @@ +// replaced by build script +const version: string = require('./../package.json').version + '-dev' +export default version diff --git a/src/wscat.ts b/src/wscat.ts new file mode 100644 index 0000000..53e8696 --- /dev/null +++ b/src/wscat.ts @@ -0,0 +1,109 @@ +/* + + /\_/\ /\_/\ + / 0 0 \ / o o \ + ====v==== ====C==== __ __ + \ W / \ V / _( )_( )_ + | | _ | | .-=(_ WEB _) + / ___ \ / / ___ \ / (__ __) + / / \ \ | / / \ \ | (__) + (((-----)))-' (((-----)))-' + / / + ( ___ ___ / + \__.=|___|E 3__|=.__/ + / ^ + +*/ + +import {ReadStream as TtyReadStream, WriteStream as TtyWriteStream} from 'tty' +import * as WebSocket from 'ws' +import {WebSocketStream} from './stream' + +export interface IOptions { + binary: boolean + inputStream: NodeJS.ReadableStream + reportClose: boolean + sendResize: string + useRaw: boolean + keepOpen: boolean + outputStream: NodeJS.WritableStream + perMessageDeflate: boolean + protocol: string +} + +export interface IConnectOptions extends IOptions { + address: string + headers: { [key: string]: string; } + rejectUnauthorized: boolean +} + +export interface IListenOptions extends IOptions { + port: number +} + +function setup(options: IOptions, socket: WebSocket) { + const stream = new WebSocketStream(socket, options) + + stream.pipe(options.outputStream) + if (socket.readyState === WebSocket.CONNECTING) { + socket.on('open', () => { options.inputStream.pipe(stream) }) + } else { + options.inputStream.pipe(stream) + } + + if (options.useRaw && options.inputStream === process.stdin && process.stdin.isTTY) { + const stdin = process.stdin as TtyReadStream + stdin.setRawMode(true) + } + + if (options.sendResize && options.outputStream === process.stdout && process.stdout.isTTY) { + const stdout = process.stdout as TtyWriteStream + const sendResize = () => { + if (socket.readyState === WebSocket.OPEN && stream.writable) { + stream.write( + options.sendResize + .replace('${columns}', String(stdout.columns)) + .replace('${rows}', String(stdout.rows))) + } + } + stdout.on('resize', sendResize) + socket.on('open', sendResize) + } + + stream.on('close', (code: number, reason: string) => { + if (options.reportClose) { + process.stdout.write(`${code}:${reason}\n`) + } + + if (options.inputStream === process.stdin && process.stdin.isTTY) { + if (options.useRaw) { + const stdin = process.stdin as TtyReadStream + stdin.setRawMode(false) + } + process.exit() + } + }) + stream.on('finish', (e) => { + if (!options.keepOpen && stream.hasWritten) { + socket.close() + } + }) +} + +export function connect(options: IConnectOptions) { + const socket = new WebSocket(options.address, options) + setup(options, socket) +} + +export function listen(options: IListenOptions) { + const serverOptions = { + clientTracking: false, + perMessageDeflate: options.perMessageDeflate, + port: options.port, + } + const server = new WebSocket.Server(serverOptions) + server.once('connection', (socket: WebSocket) => { + server.close() + setup(options, socket) + }) +} diff --git a/test/cli.sh b/test/cli.sh new file mode 100755 index 0000000..385a1b4 --- /dev/null +++ b/test/cli.sh @@ -0,0 +1,43 @@ +#!/bin/bash + +function sha256() { + echo $(shasum -p -a 256 $1 | awk '{ print $1 }') +} + +test_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +test_port=41328 + +dd bs=32768 count=42 if=/dev/urandom of=${test_dir}/testfile1 +checksum1=$(sha256 ${test_dir}/testfile1) + +wscat="${test_dir}/../node_modules/.bin/ts-node ${test_dir}/../src/cli.ts" + +$wscat --version || exit 1 + +$wscat -b -l $test_port > ${test_dir}/testfile2 & +spid=$! +sleep 1 +$wscat -b localhost:$test_port < ${test_dir}/testfile1 & +cpid=$! + +wait $cpid || exit $? +wait $spid || exit $? + +checksum2=$(sha256 ${test_dir}/testfile2) + +if [ "${checksum1}" != "${checksum2}" ]; then + echo "Checksums differ" + exit 1 +fi + +echo "bar" | $wscat -l $test_port & +sleep 1 +foo=$($wscat localhost:$test_port) + +if [ "${foo}" != "bar" ]; then + exit 1 +fi + +rm ${test_dir}/testfile* + +echo "All ok" diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..26785d1 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "declaration": true, + "lib": ["es2015"], + "module": "commonjs", + "moduleResolution": "node", + "noImplicitAny": true, + "noImplicitThis": true, + "outDir": "lib", + "strictNullChecks": true, + "target": "es6" + }, + "include": [ + "src/*.ts" + ] +} \ No newline at end of file diff --git a/tslint.json b/tslint.json new file mode 100644 index 0000000..2031e46 --- /dev/null +++ b/tslint.json @@ -0,0 +1,13 @@ +{ + "defaultSeverity": "error", + "extends": ["tslint:recommended"], + "rules": { + "max-classes-per-file": false, + "no-bitwise": false, + "no-empty": false, + "no-var-requires": false, + "quotemark": [true, "single", "avoid-escape"], + "semicolon": [true, "never"], + "triple-equals": [true, "allow-undefined-check", "allow-null-check"] + } +} \ No newline at end of file