├── src ├── client │ ├── index.mjs │ ├── polyfill.mjs │ └── connection.mjs ├── entrypoints │ ├── client.mjs │ └── server.mjs ├── server │ ├── index.mjs │ ├── options.mjs │ ├── wsproxy.mjs │ ├── http.mjs │ ├── filter.mjs │ ├── net.mjs │ └── connection.mjs ├── index.mjs ├── compat.mjs ├── compat_browser.mjs ├── logging.mjs ├── websocket.mjs ├── bin │ └── server_cli.mjs ├── extensions.mjs └── packet.mjs ├── examples ├── server_commonjs_example.js ├── server_custom_dns.mjs ├── server_example.mjs ├── wisp_v2_server.mjs ├── wisp_v2_client.mjs └── client_example.mjs ├── index.html ├── CHANGELOG.md ├── package.json ├── .gitignore ├── webpack.config.js ├── .github └── workflows │ └── main.yml ├── README.md └── LICENSE /src/client/index.mjs: -------------------------------------------------------------------------------- 1 | export { ClientConnection } from "./connection.mjs"; 2 | export { WispWebSocket, _wisp_connections } from "./polyfill.mjs"; -------------------------------------------------------------------------------- /src/entrypoints/client.mjs: -------------------------------------------------------------------------------- 1 | export * as client from "../client/index.mjs"; 2 | export * as packet from "../packet.mjs"; 3 | export * as extensions from "../extensions.mjs"; -------------------------------------------------------------------------------- /src/server/index.mjs: -------------------------------------------------------------------------------- 1 | export { ServerStream, ServerConnection} from "./connection.mjs"; 2 | export { routeRequest, parse_real_ip } from "./http.mjs"; 3 | export { options } from "./options.mjs"; -------------------------------------------------------------------------------- /src/index.mjs: -------------------------------------------------------------------------------- 1 | export * as client from "./client/index.mjs"; 2 | export * as server from "./server/index.mjs"; 3 | export * as packet from "./packet.mjs"; 4 | export * as extensions from "./extensions.mjs"; -------------------------------------------------------------------------------- /src/entrypoints/server.mjs: -------------------------------------------------------------------------------- 1 | export * as server from "../server/index.mjs"; 2 | export * as packet from "../packet.mjs"; 3 | export * as logging from "../logging.mjs"; 4 | export * as extensions from "../extensions.mjs"; -------------------------------------------------------------------------------- /src/compat.mjs: -------------------------------------------------------------------------------- 1 | //this file contains references to external node modules 2 | //it gets replaced with ./compat_browser.mjs when being bundled for the web 3 | 4 | export const global_this = globalThis; 5 | 6 | export { WebSocket, WebSocketServer } from "ws"; 7 | export * as crypto from "crypto"; 8 | 9 | export * as http from "node:http"; 10 | export * as net from "node:net"; 11 | export * as dgram from "node:dgram"; 12 | export * as dns from "node:dns/promises"; -------------------------------------------------------------------------------- /src/compat_browser.mjs: -------------------------------------------------------------------------------- 1 | //the node modules referenced by other parts of the code do not exist on the web 2 | //some of them can be replaced by the standard browser apis, others have to be ignored 3 | 4 | //compatibility for old browsers where globalThis doesn't exist 5 | export const global_this = typeof globalThis === "undefined" ? window : globalThis; 6 | 7 | export const WebSocket = global_this.WebSocket; 8 | export const crypto = global_this.crypto; 9 | export const WebSocketServer = null; 10 | export const net = null; 11 | export const dgram = null; 12 | export const dns = null; 13 | export const http = null; -------------------------------------------------------------------------------- /examples/server_commonjs_example.js: -------------------------------------------------------------------------------- 1 | const { server: wisp, logging } = require("@mercuryworkshop/wisp-js/server"); 2 | const http = require("node:http"); 3 | 4 | const server = http.createServer((req, res) => { 5 | res.writeHead(200, { "Content-Type": "text/plain" }); 6 | res.end("wisp server js rewrite"); 7 | }); 8 | 9 | logging.set_level(logging.DEBUG); 10 | wisp.options.port_whitelist = [ 11 | [5000, 6000], 12 | 80, 13 | 443 14 | ] 15 | 16 | server.on("upgrade", (req, socket, head) => { 17 | wisp.routeRequest(req, socket, head); 18 | }); 19 | 20 | server.on("listening", () => { 21 | console.log("HTTP server listening"); 22 | }); 23 | 24 | server.listen(5001, "127.0.0.1"); -------------------------------------------------------------------------------- /examples/server_custom_dns.mjs: -------------------------------------------------------------------------------- 1 | import { server as wisp, logging } from "@mercuryworkshop/wisp-js/server"; 2 | import http from "node:http"; 3 | 4 | const server = http.createServer((req, res) => { 5 | res.writeHead(200, { "Content-Type": "text/plain" }); 6 | res.end("wisp server js rewrite"); 7 | }); 8 | 9 | logging.set_level(logging.DEBUG); 10 | wisp.options.dns_method = "resolve"; 11 | wisp.options.dns_servers = ["1.1.1.3", "1.0.0.3"]; 12 | wisp.options.dns_result_order = "ipv4first"; 13 | 14 | server.on("upgrade", (req, socket, head) => { 15 | wisp.routeRequest(req, socket, head); 16 | }); 17 | 18 | server.on("listening", () => { 19 | console.log("HTTP server listening"); 20 | }); 21 | 22 | server.listen(5001, "127.0.0.1"); -------------------------------------------------------------------------------- /examples/server_example.mjs: -------------------------------------------------------------------------------- 1 | import { server as wisp, logging } from "@mercuryworkshop/wisp-js/server"; 2 | import http from "node:http"; 3 | 4 | const server = http.createServer((req, res) => { 5 | res.writeHead(200, { "Content-Type": "text/plain" }); 6 | res.end("wisp-js rewrite"); 7 | }); 8 | 9 | logging.set_level(logging.DEBUG); 10 | wisp.options.port_whitelist = [ 11 | [5000, 6000], 12 | 80, 13 | 443 14 | ] 15 | wisp.options.allow_private_ips = true; 16 | wisp.options.allow_loopback_ips = true; 17 | 18 | server.on("upgrade", (req, socket, head) => { 19 | wisp.routeRequest(req, socket, head); 20 | }); 21 | 22 | server.on("listening", () => { 23 | console.log("HTTP server listening"); 24 | }); 25 | 26 | server.listen(5001, "127.0.0.1"); -------------------------------------------------------------------------------- /examples/wisp_v2_server.mjs: -------------------------------------------------------------------------------- 1 | import { server as wisp, logging, extensions } from "@mercuryworkshop/wisp-js/server"; 2 | 3 | import http from "node:http"; 4 | 5 | const server = http.createServer((req, res) => { 6 | res.writeHead(200, { "Content-Type": "text/plain" }); 7 | res.end("wisp-js server running"); 8 | }); 9 | 10 | logging.set_level(logging.DEBUG); 11 | wisp.options.port_whitelist = [ 12 | [5000, 6000], 13 | 80, 14 | 443 15 | ] 16 | wisp.options.allow_private_ips = true; 17 | wisp.options.allow_loopback_ips = true; 18 | wisp.options.wisp_version = 2; 19 | wisp.options.wisp_motd = "this is a wisp-js server with wisp v2 enabled."; 20 | 21 | server.on("upgrade", (req, socket, head) => { 22 | wisp.routeRequest(req, socket, head); 23 | }); 24 | 25 | server.on("listening", () => { 26 | console.log("HTTP server listening"); 27 | }); 28 | 29 | server.listen(5001, "127.0.0.1"); -------------------------------------------------------------------------------- /src/server/options.mjs: -------------------------------------------------------------------------------- 1 | export const options = { 2 | //destination hostname restrictions 3 | hostname_blacklist: null, 4 | hostname_whitelist: null, 5 | port_blacklist: null, 6 | port_whitelist: null, 7 | allow_direct_ip: true, 8 | allow_private_ips: false, 9 | allow_loopback_ips: false, 10 | 11 | //client connection restrictions 12 | client_ip_blacklist: null, //not implemented! 13 | client_ip_whitelist: null, //not implemented! 14 | stream_limit_per_host: -1, 15 | stream_limit_total: -1, 16 | allow_udp_streams: true, 17 | allow_tcp_streams: true, 18 | 19 | //dns options 20 | dns_ttl: 120, 21 | dns_method: "lookup", 22 | dns_servers: null, 23 | dns_result_order: "verbatim", 24 | 25 | //misc options 26 | parse_real_ip: true, 27 | parse_real_ip_from: ["127.0.0.1"], 28 | 29 | //wisp v2 options 30 | wisp_version: 2, 31 | wisp_motd: null 32 | } 33 | 34 | -------------------------------------------------------------------------------- /examples/wisp_v2_client.mjs: -------------------------------------------------------------------------------- 1 | import { client as wisp } from "@mercuryworkshop/wisp-js/client"; 2 | 3 | let ws_url = `ws://localhost:5001/ws/`; 4 | 5 | let conn = new wisp.ClientConnection(ws_url, {wisp_version: 2}); 6 | 7 | conn.onopen = () => { 8 | console.log("wisp version:", conn.wisp_version); 9 | console.log("udp enabled:", conn.udp_enabled); 10 | console.log("motd:", conn.server_motd); 11 | 12 | let stream = conn.create_stream("cloudflare.com", 80); 13 | 14 | stream.onmessage = (data) => { 15 | let text = new TextDecoder().decode(data); 16 | console.log("message from stream 1: ", text); 17 | } 18 | stream.onclose = () => { 19 | conn.close(); 20 | } 21 | 22 | let payload = "GET /cdn-cgi/trace HTTP/1.1\r\nHost: cloudflare.com\r\nConnection: close\r\n\r\n"; 23 | stream.send(new TextEncoder().encode(payload)); 24 | } 25 | 26 | conn.onclose = () => { 27 | console.log("stream 1 closed"); 28 | } 29 | -------------------------------------------------------------------------------- /src/logging.mjs: -------------------------------------------------------------------------------- 1 | export const DEBUG = 0; 2 | export const INFO = 1; 3 | export const WARN = 2; 4 | export const ERROR = 3; 5 | export const NONE = 4; 6 | export let log_level = INFO; 7 | 8 | export function get_timestamp() { 9 | let [date, time] = new Date().toJSON().split("T"); 10 | date = date.replaceAll("-", "/"); 11 | time = time.split(".")[0]; 12 | return `[${date} - ${time}]`; 13 | } 14 | 15 | export function set_level(level) { 16 | log_level = level; 17 | } 18 | 19 | export function debug(...messages) { 20 | if (log_level > DEBUG) return; 21 | console.debug(get_timestamp() + " debug:", ...messages); 22 | } 23 | 24 | export function info(...messages) { 25 | if (log_level > INFO) return; 26 | console.info(get_timestamp() + " info:", ...messages); 27 | } 28 | 29 | export function log(...messages) { 30 | if (log_level > INFO) return; 31 | console.log(get_timestamp() + " log:", ...messages); 32 | } 33 | 34 | export function warn(...messages) { 35 | if (log_level > WARN) return; 36 | console.warn(get_timestamp() + " warn:", ...messages); 37 | } 38 | 39 | export function error(...messages) { 40 | if (log_level > ERROR) return; 41 | console.error(get_timestamp() + " error:", ...messages); 42 | } 43 | 44 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 31 | 32 | 33 |

wisp client

34 | 35 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## v0.4.0 (9/26/25): 2 | - Add support for Wisp v2 on the client and server 3 | - Allow configuring the server MOTD 4 | - Fix several bugs 5 | - Improve compatibility for older browsers 6 | - Add source maps in the NPM package 7 | 8 | ## v0.3.3 (10/27/24): 9 | - Fix improper serialization of CLOSE packets 10 | 11 | ## v0.3.2 (9/30/24): 12 | - Added support for getting the client's real IP from the `X-Forwarded-For` and the `X-Real-IP` headers 13 | 14 | ## v0.3.1 (9/27/24): 15 | - Add an option to the server CLI for setting the config based on a JSON string 16 | 17 | ## v0.3.0 (9/26/24): 18 | - Add server options for advanced DNS settings 19 | - Implement multiple modes for DNS resolution 20 | - Add support for setting custom DNS servers 21 | 22 | ## v0.2.2 (9/25/24): 23 | - Add server options for restricting access to certain IP ranges 24 | - Add a DNS cache for improved performance 25 | 26 | ## v0.2.1 (9/19/24): 27 | - Add support for JSON configuration files in the server CLI 28 | 29 | ## v0.2.0 (9/19/24): 30 | - Added a CLI interface to the Wisp server 31 | - Implemented a new `npx wisp-js-server` command 32 | 33 | ## v0.1.2 (9/18/24): 34 | - Use Webpack for bundling the dist files 35 | - Add CommonJS support 36 | 37 | ## v0.1.1 (7/18/24): 38 | - Enable TCP_NODELAY on the underlying TCP sockets 39 | - Fix errors related to resuming sockets 40 | 41 | ## v0.1.0 (7/13/24): 42 | - Initial release on NPM 43 | - Includes async Wisp server 44 | - Includes rewritten Wisp client and packet parsing 45 | - Add configurable logging options 46 | - Add whitelist/blacklist options for the server -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@mercuryworkshop/wisp-js", 3 | "version": "0.4.1", 4 | "description": "A client and server for the Wisp protocol, written in Javascript", 5 | "repository": { 6 | "type": "git", 7 | "url": "git+https://github.com/MercuryWorkshop/wisp-js.git" 8 | }, 9 | "author": "MercuryWorkshop", 10 | "license": "AGPL-3.0", 11 | "bugs": { 12 | "url": "https://github.com/MercuryWorkshop/wisp-js/issues" 13 | }, 14 | "homepage": "https://github.com/MercuryWorkshop/wisp-js#readme", 15 | "main": "./src/index.mjs", 16 | "exports": { 17 | ".": { 18 | "import": "./src/index.mjs", 19 | "require": "./dist/wisp-full.cjs" 20 | }, 21 | "./client": { 22 | "import": "./src/entrypoints/client.mjs", 23 | "require": "./dist/wisp-client.cjs" 24 | }, 25 | "./server": { 26 | "import": "./src/entrypoints/server.mjs", 27 | "require": "./dist/wisp-server.cjs" 28 | } 29 | }, 30 | "browser": { 31 | ".": "./src/index.mjs", 32 | "./client": "./src/entrypoints/client.mjs", 33 | "./server": "./src/entrypoints/server.mjs", 34 | "./src/compat.mjs": "./src/compat_browser.mjs" 35 | }, 36 | "files": [ 37 | "dist", 38 | "src" 39 | ], 40 | "scripts": { 41 | "build": "webpack", 42 | "build:prod": "webpack --mode=production", 43 | "dev": "webpack --watch", 44 | "server_cli": "node ./src/bin/server_cli.mjs", 45 | "prepack": "npm run build:prod" 46 | }, 47 | "bin": { 48 | "wisp-js-server": "src/bin/server_cli.mjs" 49 | }, 50 | "dependencies": { 51 | "bufferutil": "^4.0.9", 52 | "commander": "^14.0.2", 53 | "ipaddr.js": "^2.3.0", 54 | "ws": "^8.18.3" 55 | }, 56 | "devDependencies": { 57 | "@babel/core": "^7.28.5", 58 | "@babel/preset-env": "^7.28.5", 59 | "babel-loader": "^10.0.0", 60 | "webpack": "^5.103.0", 61 | "webpack-cli": "^6.0.1" 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/server/wsproxy.mjs: -------------------------------------------------------------------------------- 1 | import * as logging from "../logging.mjs"; 2 | import * as filter from "./filter.mjs"; 3 | import { stream_types } from "../packet.mjs"; 4 | import { AsyncWebSocket } from "../websocket.mjs"; 5 | import { NodeTCPSocket } from "./net.mjs"; 6 | 7 | export class WSProxyConnection { 8 | constructor(ws, path) { 9 | let [hostname, port] = path.split("/").pop().split(":"); 10 | this.hostname = hostname.trim(); 11 | this.port = parseInt(port); 12 | this.ws = new AsyncWebSocket(ws); 13 | } 14 | 15 | async setup() { 16 | await this.ws.connect(); 17 | 18 | //check that the destination host/ip is allowed 19 | let err_code = await filter.is_stream_allowed(null, stream_types.TCP, this.hostname, this.port); 20 | if (err_code !== 0) { 21 | logging.info(`Refusing to create a wsproxy connection to ${this.hostname}:${this.port}`); 22 | this.ws.close(); 23 | throw new filter.AccessDeniedError(); 24 | } 25 | 26 | //connect to the tcp host after we are certain that it's safe to do so 27 | this.socket = new NodeTCPSocket(this.hostname, this.port); 28 | await this.socket.connect(); 29 | 30 | //start the proxy tasks in the background 31 | this.tcp_to_ws().catch((error) => { 32 | logging.error(`a tcp to ws task (wsproxy) encountered an error - ${error}`); 33 | }); 34 | this.ws_to_tcp().catch((error) => { 35 | logging.error(`a ws to tcp task (wsproxy) encountered an error - ${error}`); 36 | }); 37 | } 38 | 39 | async tcp_to_ws() { 40 | while (true) { 41 | let data = await this.socket.recv(); 42 | if (data == null) { 43 | break; 44 | } 45 | this.socket.pause(); 46 | await this.ws.send(data); 47 | this.socket.resume(); 48 | } 49 | await this.ws.close(); 50 | } 51 | 52 | async ws_to_tcp() { 53 | while (true) { 54 | let data; 55 | data = await this.ws.recv(); 56 | if (data == null) { 57 | break; //websocket closed 58 | } 59 | await this.socket.send(data); 60 | } 61 | await this.socket.close(); 62 | } 63 | } -------------------------------------------------------------------------------- /examples/client_example.mjs: -------------------------------------------------------------------------------- 1 | import { client } from "@mercuryworkshop/wisp-js/client"; 2 | const { ClientConnection, WispWebSocket, _wisp_connections } = client; 3 | 4 | let ws_url = `ws://localhost:5001/ws/`; 5 | if (typeof process === "undefined") { 6 | ws_url = location.href.replace("http", "ws"); 7 | } 8 | 9 | function run_demo() { 10 | let ws = new WispWebSocket(ws_url+"phishing.testcategory.com:80"); 11 | ws.binaryType = "arraybuffer"; 12 | ws.addEventListener("open", () => { 13 | let payload = "GET / HTTP/1.1\r\nHost: phishing.testcategory.com\r\nConnection: keepalive\r\n\r\n"; 14 | ws.send(payload); 15 | }); 16 | ws.addEventListener("message", (event) => { 17 | let text = new TextDecoder().decode(event.data); 18 | console.log("message from stream 1: ", text); 19 | }); 20 | ws.addEventListener("close", () => { 21 | console.log("stream 1 closed"); 22 | }); 23 | 24 | let ws2 = new WispWebSocket(ws_url+"www.google.com:80"); 25 | ws2.binaryType = "arraybuffer"; 26 | ws2.addEventListener("open", () => { 27 | let payload = "GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n"; 28 | ws2.send(payload); 29 | }); 30 | ws2.addEventListener("message", (event) => { 31 | let text = new TextDecoder().decode(event.data); 32 | console.log("message from stream 2: ", text); 33 | }); 34 | ws2.addEventListener("close", () => { 35 | console.log("stream 2 closed"); 36 | }); 37 | 38 | let conn = new ClientConnection(ws_url); 39 | conn.onopen = () => { 40 | let stream = conn.create_stream("127.0.0.1", 5553, "udp"); 41 | stream.onmessage = (data) => { 42 | console.log("message from stream 3: ", new TextDecoder().decode(data)); 43 | } 44 | stream.send(new TextEncoder().encode("hello")); 45 | } 46 | conn.onclose = () => { 47 | console.log("stream 3 closed"); 48 | } 49 | } 50 | 51 | globalThis.ClientConnection = ClientConnection; 52 | globalThis.WispWebSocket = WispWebSocket; 53 | globalThis.ws_url = ws_url; 54 | globalThis.run_demo = run_demo; 55 | globalThis._wisp_connections = _wisp_connections; 56 | 57 | run_demo(); 58 | -------------------------------------------------------------------------------- /src/server/http.mjs: -------------------------------------------------------------------------------- 1 | import * as logging from "../logging.mjs"; 2 | import * as compat from "../compat.mjs"; 3 | 4 | import { options } from "./options.mjs"; 5 | import { AccessDeniedError } from "./filter.mjs"; 6 | import { ServerConnection, HandshakeError } from "./connection.mjs"; 7 | import { WSProxyConnection } from "./wsproxy.mjs"; 8 | import { is_node, assert_on_node } from "./net.mjs"; 9 | 10 | let ws_server = null; 11 | if (is_node) { 12 | ws_server = new compat.WebSocketServer({ noServer: true }); 13 | } 14 | 15 | export function parse_real_ip(headers, client_ip) { 16 | if (options.parse_real_ip && options.parse_real_ip_from.includes(client_ip)) { 17 | if (headers["x-forwarded-for"]) { 18 | return headers["x-forwarded-for"].split(",")[0].trim(); 19 | } 20 | else if (headers["x-real-ip"]) { 21 | return headers["x-real-ip"]; 22 | } 23 | } 24 | return client_ip; 25 | } 26 | 27 | export function routeRequest(request, socket, head, conn_options={}) { 28 | assert_on_node(); 29 | if (request.headers["sec-websocket-protocol"] && options.wisp_version === 2) 30 | conn_options.wisp_version = 2; 31 | else 32 | conn_options.wisp_version = 1; 33 | 34 | if (request instanceof compat.http.IncomingMessage) { 35 | ws_server.handleUpgrade(request, socket, head, (ws) => { 36 | create_connection(ws, request.url, request, conn_options); 37 | }); 38 | } 39 | else if (request instanceof compat.WebSocket) { 40 | create_connection(ws, "/", {}), conn_options; 41 | } 42 | } 43 | 44 | async function create_connection(ws, path, request, conn_options) { 45 | ws.binaryType = "arraybuffer"; 46 | let client_ip = request.socket.address().address; 47 | let real_ip = parse_real_ip(request.headers, client_ip); 48 | let origin = request.headers["origin"]; 49 | logging.info(`new connection on ${path} from ${real_ip} (origin: ${origin})`); 50 | 51 | try { 52 | if (path.endsWith("/")) { 53 | let wisp_conn = new ServerConnection(ws, path, conn_options); 54 | await wisp_conn.setup(); 55 | await wisp_conn.run(); 56 | } 57 | 58 | else { 59 | let wsproxy = new WSProxyConnection(ws, path, conn_options); 60 | await wsproxy.setup(); 61 | } 62 | } 63 | 64 | catch (error) { 65 | ws.close(); 66 | if (error instanceof HandshakeError) return; 67 | if (error instanceof AccessDeniedError) return; 68 | logging.error("Uncaught server error:\n" + (error.stack || error)); 69 | } 70 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | out 89 | 90 | # Nuxt.js build / generate output 91 | .nuxt 92 | dist 93 | 94 | # Gatsby files 95 | .cache/ 96 | # Comment in the public line in if your project uses Gatsby and not Next.js 97 | # https://nextjs.org/blog/next-9-1#public-directory-support 98 | # public 99 | 100 | # vuepress build output 101 | .vuepress/dist 102 | 103 | # vuepress v2.x temp and cache directory 104 | .temp 105 | .cache 106 | 107 | # Docusaurus cache and generated files 108 | .docusaurus 109 | 110 | # Serverless directories 111 | .serverless/ 112 | 113 | # FuseBox cache 114 | .fusebox/ 115 | 116 | # DynamoDB Local files 117 | .dynamodb/ 118 | 119 | # TernJS port file 120 | .tern-port 121 | 122 | # Stores VSCode versions used for testing VSCode extensions 123 | .vscode-test 124 | 125 | # yarn v2 126 | .yarn/cache 127 | .yarn/unplugged 128 | .yarn/build-state.yml 129 | .yarn/install-state.gz 130 | .pnp.* 131 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const common_options = { 2 | mode: "development", 3 | stats: { 4 | orphanModules: true, 5 | }, 6 | devtool: "source-map", 7 | optimization: {mangleExports: false} 8 | } 9 | 10 | const webpack_configs = [ 11 | { 12 | name: "client", 13 | entry: "./src/entrypoints/client.mjs", 14 | output: { 15 | filename: "wisp-client.js", 16 | library: { 17 | name: "wisp_client", 18 | type: "var" 19 | } 20 | }, 21 | ...common_options 22 | }, 23 | { 24 | name: "server", 25 | entry: "./src/entrypoints/server.mjs", 26 | output: { 27 | filename: "wisp-server.js", 28 | library: { 29 | name: "wisp_server", 30 | type: "var" 31 | } 32 | }, 33 | ...common_options 34 | }, 35 | { 36 | name: "full", 37 | entry: "./src/index.mjs", 38 | output: { 39 | filename: "wisp-full.js", 40 | library: { 41 | name: "wisp_full", 42 | type: "var" 43 | } 44 | }, 45 | ...common_options 46 | } 47 | ] 48 | 49 | //add es6 and commonjs module output to each webpack configuration object 50 | let new_configs = []; 51 | for (let config of webpack_configs) { 52 | let legacy_config = { 53 | ...config, 54 | name: config.name + "_legacy", 55 | module: { 56 | rules: [ 57 | { 58 | use: { 59 | loader: "babel-loader", 60 | options: { 61 | targets: "Chrome >= 64, Firefox >= 65, Safari >= 14", 62 | presets: ["@babel/preset-env"] 63 | } 64 | } 65 | } 66 | ] 67 | }, 68 | } 69 | legacy_config.output = { 70 | ...legacy_config.output, 71 | filename: config.output.filename.replace(".js", "-legacy.js"), 72 | } 73 | 74 | let es6_config = { 75 | ...config, 76 | name: config.name + "_es6", 77 | experiments: {outputModule: true}, 78 | output: { 79 | filename: config.output.filename.replace(".js", ".mjs"), 80 | library: { 81 | type: "module" 82 | } 83 | } 84 | } 85 | 86 | let cjs_config = { 87 | ...config, 88 | name: config.name + "_cjs", 89 | target: "node", 90 | output: { 91 | filename: config.output.filename.replace(".js", ".cjs"), 92 | library: { 93 | type: "commonjs" 94 | } 95 | }, 96 | externals: { 97 | "ws": "commonjs ws", 98 | "crypto": "commonjs crypto", 99 | "ipaddr.js": "commonjs ipaddr.js" 100 | }, 101 | optimization: { 102 | minimize: false 103 | } 104 | } 105 | 106 | new_configs.push(legacy_config); 107 | new_configs.push(es6_config); 108 | new_configs.push(cjs_config); 109 | } 110 | 111 | module.exports = webpack_configs.concat(new_configs);; -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | pull_request: 6 | workflow_dispatch: 7 | 8 | concurrency: 9 | group: ${{ github.workflow }}-${{ github.ref }} 10 | cancel-in-progress: true 11 | 12 | jobs: 13 | version-check: 14 | name: Check Version 15 | runs-on: ubuntu-latest 16 | outputs: 17 | version_changed: ${{ steps.check.outputs.version_changed }} 18 | new_version: ${{ steps.check.outputs.new_version }} 19 | 20 | steps: 21 | - name: Checkout Code 22 | uses: actions/checkout@v4 23 | 24 | - name: Check the version 25 | id: check 26 | run: | 27 | CURRENT_VERSION=$(jq -r .version package.json) 28 | echo "Current version: $CURRENT_VERSION" 29 | LATEST_VERSION=$(npm view @mercuryworkshop/wisp-js versions --json | jq -r '.[-1]' || echo "0.0.0") 30 | echo "Latest NPM version: $LATEST_VERSION" 31 | 32 | if [ "$LATEST_VERSION" != "$CURRENT_VERSION" ]; 33 | then 34 | echo "Version changed" 35 | echo "version_changed=true" >> "$GITHUB_OUTPUT" 36 | echo "new_version=$CURRENT_VERSION" >> "$GITHUB_OUTPUT" 37 | else 38 | echo "Version not changed" 39 | echo "version_changed=false" >> "$GITHUB_OUTPUT" 40 | fi 41 | 42 | build: 43 | name: Build wisp-js 44 | runs-on: ubuntu-latest 45 | 46 | steps: 47 | - name: Checkout code 48 | uses: actions/checkout@v4 49 | 50 | - name: Setup Node.js 51 | uses: actions/setup-node@v4 52 | with: 53 | node-version: "22" 54 | cache: "npm" 55 | 56 | - name: Install npm dependencies 57 | run: npm install 58 | 59 | - name: Pack wisp-js 60 | run: npm pack 61 | 62 | - name: Upload Artifact (packaged) 63 | uses: actions/upload-artifact@v4 64 | with: 65 | name: packaged-wisp-js 66 | path: mercuryworkshop-wisp-js-*.tgz 67 | 68 | - name: Upload Artifact 69 | uses: actions/upload-artifact@v4 70 | with: 71 | name: wisp-js 72 | path: | 73 | dist 74 | lib 75 | 76 | publish: 77 | name: Publish wisp-js to NPM 78 | runs-on: ubuntu-latest 79 | needs: [version-check, build] 80 | permissions: write-all 81 | if: github.ref == 'refs/heads/master' && needs.version-check.outputs.version_changed == 'true' 82 | 83 | steps: 84 | - name: Setup Node.js 85 | uses: actions/setup-node@v4 86 | with: 87 | node-version: "22" 88 | registry-url: "https://registry.npmjs.org" 89 | 90 | - name: Get artifacts 91 | uses: actions/download-artifact@v4 92 | with: 93 | name: packaged-wisp-js 94 | path: . 95 | 96 | - name: Update npm 97 | run: npm install -g npm@latest 98 | 99 | - name: Publish 100 | run: npm publish mercuryworkshop-wisp-js-${{ needs.version-check.outputs.new_version }}.tgz --access public --no-git-checks -------------------------------------------------------------------------------- /src/websocket.mjs: -------------------------------------------------------------------------------- 1 | //async websocket wrapper for both node and the browser 2 | 3 | import * as compat from "./compat.mjs"; 4 | import { WispPacket } from "./packet.mjs"; 5 | 6 | export function get_conn_id() { 7 | return compat.crypto.randomUUID().split("-")[0]; 8 | } 9 | 10 | //an async websocket wrapper 11 | export class AsyncWebSocket { 12 | send_buffer_size = 32*1024*1024; 13 | 14 | constructor(ws) { 15 | this.ws = ws; 16 | this.connected = false; 17 | this.data_queue = new AsyncQueue(1); 18 | } 19 | 20 | async connect() { 21 | await new Promise((resolve, reject) => { 22 | this.ws.onopen = () => { 23 | this.connected = true; 24 | resolve(); 25 | } 26 | this.ws.onmessage = (event) => { 27 | this.data_queue.put(event.data); 28 | } 29 | this.ws.onclose = () => { 30 | if (!this.connected) reject(); 31 | else this.data_queue.close(); 32 | } 33 | if (this.ws.readyState === this.ws.OPEN) { 34 | this.connected = true; 35 | resolve(); 36 | } 37 | }); 38 | } 39 | 40 | async recv() { 41 | return await this.data_queue.get(); 42 | } 43 | 44 | async send(data) { 45 | if (data instanceof WispPacket) { 46 | data = data.serialize().bytes 47 | } 48 | 49 | this.ws.send(data); 50 | if (this.ws.bufferedAmount <= this.send_buffer_size) { 51 | return; 52 | } 53 | 54 | //if the send buffer is too full, throttle the upload 55 | while (true) { 56 | if (this.ws.bufferedAmount <= this.send_buffer_size / 2) { 57 | break; 58 | } 59 | await new Promise((resolve) => {setTimeout(resolve, 10)}); 60 | } 61 | } 62 | 63 | close(code, reason) { 64 | this.ws.close(code, reason); 65 | this.data_queue.close(); 66 | } 67 | 68 | get buffered_amount() { 69 | return this.ws.bufferedAmount; 70 | } 71 | } 72 | 73 | //an async fifo queue 74 | export class AsyncQueue { 75 | constructor(max_size) { 76 | this.max_size = max_size; 77 | this.queue = []; 78 | this.put_callbacks = []; 79 | this.get_callbacks = []; 80 | } 81 | 82 | put_now(data) { 83 | this.queue.push(data); 84 | this.get_callbacks.shift()?.(); 85 | } 86 | 87 | async put(data) { 88 | if (this.size <= this.max_size) { 89 | this.put_now(data); 90 | return; 91 | } 92 | 93 | //wait until there is a place to put the item 94 | await new Promise((resolve) => { 95 | this.put_callbacks.push(resolve); 96 | }); 97 | this.put_now(data); 98 | } 99 | 100 | get_now() { 101 | this.put_callbacks.shift()?.(); 102 | return this.queue.shift(); 103 | } 104 | 105 | async get() { 106 | if (this.size > 0) { 107 | return this.get_now(); 108 | } 109 | 110 | //wait until there is an item available in the queue 111 | await new Promise((resolve) => { 112 | this.get_callbacks.push(resolve); 113 | }); 114 | return this.get_now(); 115 | } 116 | 117 | close() { 118 | this.queue = []; 119 | let callback; 120 | //resolve all pending operations 121 | while (callback = this.get_callbacks.shift()) 122 | callback(); 123 | while (callback = this.put_callbacks.shift()) 124 | callback(); 125 | } 126 | 127 | get size() { 128 | return this.queue.length; 129 | } 130 | } -------------------------------------------------------------------------------- /src/server/filter.mjs: -------------------------------------------------------------------------------- 1 | import { close_reasons, stream_types } from "../packet.mjs"; 2 | import { options } from "./options.mjs"; 3 | import * as net from "./net.mjs"; 4 | 5 | import ipaddr from "ipaddr.js"; 6 | 7 | export class AccessDeniedError extends Error {} 8 | 9 | //helper functions for the whitelist/blacklist logic 10 | function check_port_range(entry, port) { 11 | return (entry === port) || (entry[0] <= port && entry[1] >= port) 12 | } 13 | function check_whitelist(entries, filter) { 14 | let matched = false; 15 | for (let entry of entries) { 16 | if (filter(entry)) { 17 | matched = true; 18 | break 19 | } 20 | } 21 | return !matched; 22 | } 23 | function check_blacklist(entries, filter) { 24 | for (let entry of entries) { 25 | if (filter(entry)) 26 | return true; 27 | } 28 | return false; 29 | } 30 | 31 | function check_ip_range(ip, range) { 32 | return range.includes(ip.range()); 33 | } 34 | 35 | //check if an ip is blocked 36 | export function is_ip_blocked(ip_str) { 37 | if (!ipaddr.isValid(ip_str)) 38 | return false; 39 | let ip = ipaddr.parse(ip_str); 40 | 41 | let loopback_ranges = ["loopback", "unspecified"]; 42 | let private_ranges = ["broadcast", "linkLocal", "carrierGradeNat", "private", "reserved"]; 43 | 44 | if (!options.allow_loopback_ips && check_ip_range(ip, loopback_ranges)) 45 | return true; 46 | if (!options.allow_private_ips && check_ip_range(ip, private_ranges)) 47 | return true; 48 | return false; 49 | } 50 | 51 | //returns the close reason if the connection should be blocked 52 | export async function is_stream_allowed(connection, type, hostname, port) { 53 | //check if tcp or udp should be blocked 54 | if (!options.allow_tcp_streams && type === stream_types.TCP) 55 | return close_reasons.HostBlocked; 56 | if (!options.allow_udp_streams && type === stream_types.UDP) 57 | return close_reasons.HostBlocked; 58 | 59 | //check the hostname whitelist/blacklist 60 | if (options.hostname_whitelist) { 61 | if (check_whitelist(options.hostname_whitelist, (entry) => entry.test(hostname))) 62 | return close_reasons.HostBlocked; 63 | } 64 | else if (options.hostname_blacklist) { 65 | if (check_blacklist(options.hostname_blacklist, (entry) => entry.test(hostname))) 66 | return close_reasons.HostBlocked; 67 | } 68 | 69 | //check if the port is blocked 70 | if (options.port_whitelist) { 71 | if (check_whitelist(options.port_whitelist, (entry) => check_port_range(entry, port))) 72 | return close_reasons.HostBlocked; 73 | } 74 | else if (options.port_blacklist) { 75 | if (check_blacklist(options.port_blacklist, (entry) => check_port_range(entry, port))) 76 | return close_reasons.HostBlocked; 77 | } 78 | 79 | //check if the destination ip is blocked 80 | let ip_str = hostname; 81 | if (ipaddr.isValid(hostname)) { 82 | if (!options.allow_direct_ip) 83 | return close_reasons.HostBlocked; 84 | } 85 | else { 86 | try { //look up the ip to make sure that the resolved address is allowed 87 | ip_str = await net.lookup_ip(hostname); 88 | } 89 | catch {} 90 | } 91 | if (is_ip_blocked(ip_str)) 92 | return close_reasons.HostBlocked; 93 | 94 | //don't check stream counts if there isn't an associated wisp connection (with wsproxy for example) 95 | if (!connection) 96 | return 0; 97 | 98 | //check for stream count limits 99 | if (options.stream_limit_total !== -1 && Object.keys(connection.streams).length >= options.stream_limit_total) 100 | return close_reasons.ConnThrottled; 101 | if (options.stream_limit_per_host !== -1) { 102 | let streams_per_host = 0; 103 | for (let stream of connection.streams) { 104 | if (stream.socket.hostname === hostname) { 105 | streams_per_host++; 106 | } 107 | } 108 | if (streams_per_host >= options.stream_limit_per_host) 109 | return close_reasons.ConnThrottled; 110 | } 111 | 112 | return 0; 113 | } -------------------------------------------------------------------------------- /src/bin/server_cli.mjs: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import http from "node:http"; 4 | import path from "node:path"; 5 | import { promises as fs } from "fs"; 6 | 7 | import { server as wisp, logging, extensions } from "@mercuryworkshop/wisp-js/server"; 8 | import { createRequire } from "module"; 9 | import { Command } from "commander"; 10 | 11 | //find own program version from package.json 12 | //https://stackoverflow.com/a/76782867/21330993 13 | const package_json = createRequire(import.meta.url)("./../../package.json"); 14 | const version = package_json.version; 15 | 16 | //parse arguments 17 | const program = new Command(); 18 | program 19 | .name("wisp-js-server") 20 | .description(`A Wisp server implementation written in Javascript. (v${version})`) 21 | .version(version); 22 | 23 | program 24 | .option("-H, --host ", "The hostname the server will listen on.", "127.0.0.1") 25 | .option("-P, --port ", "The port number to run the server on.", parseInt(process.env.PORT || "5001")) 26 | .option("-L, --logging ", "The log level to use. This is either DEBUG, INFO, WARN, ERROR, or NONE.", "INFO") 27 | .option("-S, --static ", "The directory to serve static files from. (optional)") 28 | .option("-C, --config ", "The path to your Wisp server config file. This is the same format as `wisp.options` in the API. (optional)") 29 | .option("-O, --options ", "A JSON string to set the Wisp config without using a file. (optional)") 30 | 31 | program.parse(); 32 | const opts = program.opts(); 33 | 34 | //set up server settings 35 | opts.logging = opts.logging.toUpperCase(); 36 | if (["DEBUG", "INFO", "WARN", "ERROR", "NONE"].includes(opts.logging)) { 37 | logging.set_level(logging[opts.logging]); 38 | } 39 | else { 40 | console.error("Invalid log level: " + opts.logging); 41 | console.error("Valid choices: DEBUG, INFO, WARN, ERROR, NONE"); 42 | process.exit(1); 43 | } 44 | 45 | if (opts.static) { 46 | opts.static = path.resolve(opts.static); 47 | logging.info("Serving static files from: " + opts.static); 48 | } 49 | 50 | if (opts.config) { 51 | opts.config = path.resolve(opts.config); 52 | logging.info("Using config file: " + opts.config); 53 | 54 | let data = await fs.readFile(opts.config); 55 | let config = JSON.parse(data); 56 | for (let [key, value] of Object.entries(config)) 57 | wisp.options[key] = value; 58 | } 59 | 60 | if (opts.options) { 61 | opts.options = JSON.parse(opts.options); 62 | for (let [key, value] of Object.entries(opts.options)) 63 | wisp.options[key] = value; 64 | } 65 | 66 | //start the wisp server 67 | const mime_types = { 68 | "ico": "image/x-icon", 69 | "html": "text/html", 70 | "js": "text/javascript", 71 | "mjs": "text/javascript", 72 | "json": "application/json", 73 | "css": "text/css", 74 | "png": "image/png", 75 | "jpg": "image/jpeg", 76 | "wav": "audio/wav", 77 | "mp3": "audio/mpeg", 78 | "svg": "image/svg+xml", 79 | "pdf": "application/pdf", 80 | "zip": "application/zip", 81 | "ttf": "application/x-font-ttf" 82 | }; 83 | 84 | const server = http.createServer(async (req, res) => { 85 | let client_ip = req.socket.address().address; 86 | let real_ip = wisp.parse_real_ip(req.headers, client_ip); 87 | logging.info(`HTTP ${req.method} ${req.url} from ${real_ip}`) 88 | 89 | if (!opts.static) { 90 | res.writeHead(200, { "Content-Type": "text/plain" }); 91 | res.end(`wisp-js-server v${version} is running`); 92 | return 93 | } 94 | 95 | try { 96 | let parsed_url = new URL(req.url, "http://localhost/"); 97 | let served_path = path.join(opts.static, parsed_url.pathname); 98 | 99 | let path_stat = await fs.stat(served_path); 100 | if (path_stat.isDirectory()) { 101 | served_path = path.join(served_path, "index.html"); 102 | } 103 | 104 | let data = await fs.readFile(served_path); 105 | let file_ext = served_path.split(".").reverse()[0]; 106 | let content_type = mime_types[file_ext] || "application/octet-stream"; 107 | 108 | res.writeHead(200, {"Content-Type": content_type}); 109 | res.end(data); 110 | } 111 | 112 | catch (err) { 113 | if (err.code == "ENOENT") { 114 | res.writeHead(404, {"Content-Type": "text/plain"}); 115 | res.end("404 not found"); 116 | } 117 | else { 118 | res.writeHead(500, {"Content-Type": "text/plain"}); 119 | res.end("500 internal server error:\n" + err); 120 | } 121 | } 122 | }); 123 | 124 | server.on("upgrade", (req, socket, head) => { 125 | wisp.routeRequest(req, socket, head); 126 | }); 127 | 128 | server.on("listening", () => { 129 | logging.info(`HTTP server listening on ${opts.host}:${opts.port}`); 130 | }); 131 | 132 | server.listen(parseInt(opts.port), opts.host); -------------------------------------------------------------------------------- /src/extensions.mjs: -------------------------------------------------------------------------------- 1 | import { WispBuffer } from "./packet.mjs"; 2 | 3 | class EmptyPayload { 4 | constructor() {} 5 | static parse() { 6 | return new EmptyPayload(); 7 | } 8 | serialize() { 9 | return new WispBuffer(0); 10 | } 11 | } 12 | 13 | export class BaseExtension { 14 | static id = 0x00; 15 | static name = ""; 16 | 17 | static Server = EmptyPayload; 18 | static Client = EmptyPayload; 19 | 20 | constructor({server_config, client_config} = {}) { 21 | this.id = this.constructor.id; 22 | this.name = this.constructor.name; 23 | if (server_config) 24 | this.payload = new this.constructor.Server(server_config); 25 | else if (client_config) 26 | this.payload = new this.constructor.Client(client_config); 27 | } 28 | static parse(ext_class, buffer, role) { 29 | let extension = new ext_class({}); 30 | if (role === "client") 31 | extension.payload = ext_class.Client.parse(buffer.slice(5)); 32 | else if (role === "server") 33 | extension.payload = ext_class.Server.parse(buffer.slice(5)); 34 | else 35 | throw TypeError("invalid role"); 36 | return extension; 37 | } 38 | serialize() { 39 | let buffer = new WispBuffer(5); 40 | let payload_buffer = this.payload.serialize(); 41 | buffer.view.setInt8(0, this.constructor.id); 42 | buffer.view.setUint32(1, payload_buffer.size, true); 43 | return buffer.concat(payload_buffer); 44 | } 45 | } 46 | 47 | export class UDPExtension extends BaseExtension { 48 | static id = 0x01; 49 | static name = "UDP"; 50 | } 51 | 52 | export class PasswordAuthExtension extends BaseExtension { 53 | static id = 0x02; 54 | static name = "Password Authentication"; 55 | 56 | static Server = class { 57 | constructor({required = 1}) { 58 | this.required = required ? 1 : 0; 59 | } 60 | static parse(buffer) { 61 | return new PasswordAuthExtension.Server({ 62 | required: buffer.view.getUint8(0) 63 | }); 64 | } 65 | serialize() { 66 | let buffer = new WispBuffer(1); 67 | buffer.view.setUint8(0, this.required); 68 | return buffer; 69 | } 70 | } 71 | 72 | static Client = class { 73 | constructor({username, password}) { 74 | this.username = username; 75 | this.password = password; 76 | } 77 | static parse(buffer) { 78 | let username_len = buffer.view.getUint8(0); 79 | let password_len = buffer.view.getUint16(1, true); 80 | let password_index = username_len + 3; 81 | return new PasswordAuthExtension.Client({ 82 | username: buffer.slice(3, username_len).get_string(), 83 | password: buffer.slice(password_index, password_len).get_string() 84 | }); 85 | } 86 | serialize() { 87 | let username_buffer = new WispBuffer(this.username); 88 | let password_buffer = new WispBuffer(this.password); 89 | let buffer = new WispBuffer(3); 90 | buffer.view.setUint8(0, username_buffer.size); 91 | buffer.view.setUint16(1, password_buffer.size, true); 92 | return buffer.concat(username_buffer).concat(password_buffer); 93 | } 94 | } 95 | } 96 | 97 | export class MOTDExtension extends BaseExtension { 98 | static id = 0x04; 99 | static name = "Server MOTD"; 100 | 101 | static Server = class { 102 | constructor({message}) { 103 | this.message = message; 104 | } 105 | static parse(buffer) { 106 | return new MOTDExtension.Server({ 107 | message: buffer.get_string() 108 | }); 109 | } 110 | serialize() { 111 | return new WispBuffer(this.message); 112 | } 113 | } 114 | 115 | static Client = EmptyPayload; 116 | } 117 | 118 | export function parse_extensions(payload_buffer, valid_extensions, role) { 119 | let index = 0; 120 | let parsed_extensions = []; 121 | while (payload_buffer.size) { 122 | let ext_id = payload_buffer.view.getUint8(index); 123 | let ext_len = payload_buffer.view.getUint32(index + 1, true); 124 | let ext_payload = payload_buffer.slice(0, 5 + ext_len); 125 | let ext_class; 126 | for (let extension of valid_extensions) { 127 | if (extension.id !== ext_id) 128 | continue; 129 | ext_class = extension.constructor; 130 | break; 131 | } 132 | if (ext_class) { 133 | let ext_parsed = BaseExtension.parse(ext_class, ext_payload, role); 134 | parsed_extensions.push(ext_parsed); 135 | } 136 | payload_buffer = payload_buffer.slice(5 + ext_len); 137 | } 138 | return parsed_extensions; 139 | } 140 | 141 | export function serialize_extensions(extensions) {{ 142 | let ext_buffer = new WispBuffer(0); 143 | for (let extension of extensions) { 144 | ext_buffer = ext_buffer.concat(extension.serialize()); 145 | } 146 | return ext_buffer; 147 | }} 148 | 149 | export const extensions_map = { 150 | 0x01: UDPExtension, 151 | 0x02: PasswordAuthExtension, 152 | 0x04: MOTDExtension 153 | } -------------------------------------------------------------------------------- /src/client/polyfill.mjs: -------------------------------------------------------------------------------- 1 | import { global_this } from "../compat.mjs"; 2 | import { ClientConnection } from "./connection.mjs"; 3 | 4 | //polyfill the DOM Websocket API so that applications using wsproxy can easily use wisp with minimal changes 5 | 6 | const RealCloseEvent = (global_this.CloseEvent || Event); 7 | export const _wisp_connections = {}; 8 | 9 | export class WispWebSocket extends EventTarget { 10 | constructor(url, protocols=null, options = {}) { 11 | super(); 12 | this.url = url; 13 | this.protocols = protocols; 14 | this.options = options; 15 | this.binaryType = "blob"; 16 | this.stream = null; 17 | this.connection = null; 18 | 19 | //legacy event handlers 20 | this.onopen = () => {}; 21 | this.onerror = () => {}; 22 | this.onmessage = () => {}; 23 | this.onclose = () => {}; 24 | 25 | this.CONNECTING = 0; 26 | this.OPEN = 1; 27 | this.CLOSING = 2; 28 | this.CLOSED = 3; 29 | this._ready_state = this.CONNECTING; 30 | 31 | //parse the wsproxy url 32 | let url_split = this.url.split("/"); 33 | let wsproxy_path = url_split.pop().split(":"); 34 | this.host = wsproxy_path[0]; 35 | this.port = parseInt(wsproxy_path[1]); 36 | this.real_url = url_split.join("/") + "/"; 37 | 38 | this.init_connection(); 39 | } 40 | 41 | on_conn_close() { 42 | this._ready_state = this.CLOSED; 43 | if (_wisp_connections[this.real_url]) { 44 | this.onerror(new Event("error")); 45 | this.dispatchEvent(new Event("error")); 46 | } 47 | delete _wisp_connections[this.real_url]; 48 | } 49 | 50 | init_connection() { 51 | //create the stream 52 | this.connection = _wisp_connections[this.real_url]; 53 | 54 | if (!this.connection) { 55 | this.connection = new ClientConnection(this.real_url, this.options); 56 | this.connection.onopen = () => { 57 | this.init_stream(); 58 | }; 59 | this.connection.onclose = () => { 60 | this.on_conn_close() 61 | }; 62 | this.connection.onerror = () => { 63 | this.on_conn_close() 64 | }; 65 | _wisp_connections[this.real_url] = this.connection; 66 | } 67 | else if (!this.connection.connected) { 68 | let old_onopen = this.connection.onopen; 69 | this.connection.onopen = () => { 70 | old_onopen(); 71 | this.init_stream(); 72 | }; 73 | } 74 | else { 75 | this.connection = _wisp_connections[this.real_url]; 76 | this.init_stream(); 77 | } 78 | } 79 | 80 | init_stream() { 81 | this._ready_state = this.OPEN; 82 | this.stream = this.connection.create_stream(this.host, this.port); 83 | 84 | this.stream.onmessage = (raw_data) => { 85 | let data; 86 | if (this.binaryType == "blob") { 87 | data = new Blob(raw_data); 88 | } 89 | else if (this.binaryType == "arraybuffer") { 90 | data = raw_data.buffer; 91 | } 92 | else { 93 | throw "invalid binaryType string"; 94 | } 95 | let msg_event = new MessageEvent("message", {data: data}); 96 | this.onmessage(msg_event); 97 | this.dispatchEvent(msg_event); 98 | }; 99 | 100 | this.stream.onclose = (reason) => { 101 | this._ready_state = this.CLOSED; 102 | let close_event = new RealCloseEvent("close", {code: reason}); 103 | this.onclose(close_event); 104 | this.dispatchEvent(close_event); 105 | }; 106 | 107 | let open_event = new Event("open"); 108 | this.onopen(open_event); 109 | this.dispatchEvent(open_event); 110 | } 111 | 112 | send(data) { 113 | let data_array; 114 | 115 | if (data instanceof Uint8Array) { 116 | data_array = data; 117 | } 118 | else if (typeof data === "string") { 119 | data_array = new TextEncoder().encode(data); 120 | } 121 | else if (data instanceof Blob) { 122 | data.arrayBuffer().then(array_buffer => { 123 | this.send(array_buffer); 124 | }); 125 | return; 126 | } 127 | else if (data instanceof ArrayBuffer) { 128 | data_array = new Uint8Array(data); 129 | } 130 | //dataview objects or any other typedarray 131 | else if (ArrayBuffer.isView(data)) { 132 | data_array = new Uint8Array(data.buffer); 133 | } 134 | else { 135 | throw "invalid data type to be sent"; 136 | } 137 | 138 | if (!this.stream) { 139 | throw "websocket is not ready"; 140 | } 141 | this.stream.send(data_array); 142 | } 143 | 144 | close() { 145 | this.stream.close(0x02); 146 | } 147 | 148 | get bufferedAmount() { 149 | let total = 0; 150 | for (let msg of this.stream.send_buffer) { 151 | total += msg.length; 152 | } 153 | return total; 154 | } 155 | 156 | get extensions() { 157 | return ""; 158 | } 159 | 160 | get protocol() { 161 | return "binary"; 162 | } 163 | 164 | get readyState() { 165 | return this._ready_state; 166 | } 167 | } -------------------------------------------------------------------------------- /src/packet.mjs: -------------------------------------------------------------------------------- 1 | //shared packet parsing / serialization code 2 | 3 | const text_encoder = new TextEncoder(); 4 | const encode_text = text_encoder.encode.bind(text_encoder); 5 | const text_decoder = new TextDecoder(); 6 | const decode_text = text_decoder.decode.bind(text_decoder); 7 | 8 | export class WispBuffer { 9 | constructor(data) { 10 | if (data instanceof Uint8Array) { 11 | this.from_array(data); 12 | } 13 | else if (typeof data === "number") { 14 | this.from_array(new Uint8Array(data)); 15 | } 16 | else if (typeof data === "string") { 17 | this.from_array(encode_text(data)); 18 | } 19 | else { 20 | console.trace(); 21 | throw "invalid data type passed to wisp buffer constructor"; 22 | } 23 | } 24 | 25 | from_array(bytes) { 26 | this.size = bytes.length; 27 | this.bytes = bytes; 28 | this.view = new DataView(bytes.buffer); 29 | } 30 | 31 | concat(buffer) { 32 | let new_buffer = new WispBuffer(this.size + buffer.size); 33 | new_buffer.bytes.set(this.bytes, 0); 34 | new_buffer.bytes.set(buffer.bytes, this.size); 35 | return new_buffer; 36 | } 37 | 38 | slice(index, size) { 39 | let bytes_slice = this.bytes.slice(index, size); 40 | return new WispBuffer(bytes_slice); 41 | } 42 | 43 | get_string() { 44 | return text_decoder.decode(this.bytes); 45 | } 46 | } 47 | 48 | export class WispPacket { 49 | static min_size = 5; 50 | constructor({type, stream_id, payload, payload_bytes }) { 51 | this.type = type; 52 | this.stream_id = stream_id; 53 | this.payload_bytes = payload_bytes; 54 | this.payload = payload; 55 | } 56 | static parse(buffer) { 57 | return new WispPacket({ 58 | type: buffer.view.getUint8(0), 59 | stream_id: buffer.view.getUint32(1, true), 60 | payload_bytes: buffer.slice(5) 61 | }); 62 | } 63 | static parse_all(buffer) { 64 | if (buffer.size < WispPacket.min_size) { 65 | throw TypeError("packet too small"); 66 | } 67 | let packet = WispPacket.parse(buffer); 68 | let payload_class = packet_classes[packet.type]; 69 | if (typeof payload_class === "undefined") { 70 | throw TypeError("invalid packet type"); 71 | } 72 | if (packet.payload_bytes.size < payload_class.size) { 73 | throw TypeError("payload too small"); 74 | } 75 | packet.payload = payload_class.parse(packet.payload_bytes); 76 | return packet; 77 | } 78 | serialize() { 79 | let buffer = new WispBuffer(5); 80 | buffer.view.setUint8(0, this.type); 81 | buffer.view.setUint32(1, this.stream_id, true); 82 | buffer = buffer.concat(this.payload.serialize()); 83 | return buffer; 84 | } 85 | } 86 | 87 | export class ConnectPayload { 88 | static min_size = 3; 89 | static type = 0x01; 90 | static name = "CONNECT"; 91 | constructor({stream_type, port, hostname}) { 92 | this.stream_type = stream_type; 93 | this.port = port; 94 | this.hostname = hostname; 95 | } 96 | static parse(buffer) { 97 | return new ConnectPayload({ 98 | stream_type: buffer.view.getUint8(0), 99 | port: buffer.view.getUint16(1, true), 100 | hostname: decode_text(buffer.slice(3).bytes) 101 | }); 102 | } 103 | serialize() { 104 | let buffer = new WispBuffer(3); 105 | buffer.view.setUint8(0, this.stream_type); 106 | buffer.view.setUint16(1, this.port, true); 107 | buffer = buffer.concat(new WispBuffer(this.hostname)); 108 | return buffer; 109 | } 110 | } 111 | 112 | export class DataPayload { 113 | static min_size = 0; 114 | static type = 0x02; 115 | static name = "DATA"; 116 | constructor({data}) { 117 | this.data = data; 118 | } 119 | static parse(buffer) { 120 | return new DataPayload({ 121 | data: buffer 122 | }); 123 | } 124 | serialize() { 125 | return this.data; 126 | } 127 | } 128 | 129 | export class ContinuePayload { 130 | static type = 0x03; 131 | static name = "CONTINUE"; 132 | constructor({buffer_remaining}) { 133 | this.buffer_remaining = buffer_remaining; 134 | } 135 | static parse(buffer) { 136 | return new ContinuePayload({ 137 | buffer_remaining: buffer.view.getUint32(0, true), 138 | }); 139 | } 140 | serialize() { 141 | let buffer = new WispBuffer(4); 142 | buffer.view.setUint32(0, this.buffer_remaining, true); 143 | return buffer; 144 | } 145 | } 146 | 147 | export class ClosePayload { 148 | static min_size = 1; 149 | static type = 0x04; 150 | static name = "CLOSE"; 151 | constructor({reason}) { 152 | this.reason = reason; 153 | } 154 | static parse(buffer) { 155 | return new ClosePayload({ 156 | reason: buffer.view.getUint8(0), 157 | }); 158 | } 159 | serialize() { 160 | let buffer = new WispBuffer(1); 161 | buffer.view.setUint8(0, this.reason); 162 | return buffer; 163 | } 164 | } 165 | 166 | export class InfoPayload { 167 | static min_size = 2; 168 | static type = 0x05; 169 | static name = "INFO"; 170 | constructor({major_ver, minor_ver, extensions}) { 171 | this.major_ver = major_ver; 172 | this.minor_ver = minor_ver; 173 | this.extensions = extensions; 174 | } 175 | static parse(buffer) { 176 | return new InfoPayload({ 177 | major_ver: buffer.view.getUint8(0), 178 | minor_ver: buffer.view.getUint8(1), 179 | extensions: buffer.slice(2) 180 | }); 181 | } 182 | serialize() { 183 | let buffer = new WispBuffer(2); 184 | buffer.view.setUint8(0, this.major_ver); 185 | buffer.view.setUint8(1, this.minor_ver); 186 | return buffer.concat(this.extensions); 187 | } 188 | } 189 | 190 | export const packet_classes = { 191 | 0x01: ConnectPayload, 192 | 0x02: DataPayload, 193 | 0x03: ContinuePayload, 194 | 0x04: ClosePayload, 195 | 0x05: InfoPayload 196 | } 197 | 198 | export const packet_types = { 199 | CONNECT: 0x01, 200 | DATA: 0x02, 201 | CONTINUE: 0x03, 202 | CLOSE: 0x04, 203 | INFO: 0x05 204 | } 205 | 206 | export const stream_types = { 207 | TCP: 0x01, 208 | UDP: 0x02 209 | } 210 | 211 | export const close_reasons = { 212 | //client/server close reasons 213 | Unknown: 0x01, 214 | Voluntary: 0x02, 215 | NetworkError: 0x03, 216 | IncompatibleExtensions: 0x04, 217 | 218 | //server only close reasons 219 | InvalidInfo: 0x41, 220 | UnreachableHost: 0x42, 221 | NoResponse: 0x43, 222 | ConnRefused: 0x44, 223 | TransferTimeout: 0x47, 224 | HostBlocked: 0x48, 225 | ConnThrottled: 0x49, 226 | 227 | //client only close reasons 228 | ClientError: 0x81, 229 | 230 | //extension specific close reasons 231 | AuthBadPassword: 0xc0, 232 | AuthBadSignature: 0xc1, 233 | AuthMissingCredentials: 0xc2 234 | } -------------------------------------------------------------------------------- /src/server/net.mjs: -------------------------------------------------------------------------------- 1 | import * as logging from "../logging.mjs"; 2 | import { AsyncQueue } from "../websocket.mjs"; 3 | import { options } from "./options.mjs"; 4 | import { net, dgram, dns } from "../compat.mjs"; 5 | 6 | //wrappers for node networking apis 7 | //in the browser these can be redefined to allow for custom transports 8 | 9 | export const is_node = (typeof process !== "undefined"); 10 | 11 | const dns_cache = new Map(); 12 | let dns_servers = null; 13 | let resolver = null; 14 | 15 | export function assert_on_node() { 16 | if (!is_node) { 17 | throw new Error("not running on node.js"); 18 | } 19 | } 20 | 21 | //wrapper for node resolver methods 22 | //resolve4 and resolve6 need to be wrapped to work around a nodejs bug 23 | function resolve4(hostname) { 24 | return resolver.resolve4(hostname); 25 | } 26 | function resolve6(hostname) { 27 | return resolver.resolve6(hostname); 28 | } 29 | async function resolve_with_fallback(resolve_first, resolve_after, hostname) { 30 | try { 31 | return (await resolve_first(hostname))[0]; 32 | } 33 | catch { 34 | return (await resolve_after(hostname))[0]; 35 | } 36 | } 37 | 38 | //a wrapper for the actual dns lookup 39 | async function perform_lookup(hostname) { 40 | //resolve using system dns 41 | if (options.dns_method === "lookup") { 42 | let result = await dns.lookup(hostname, {order: options.dns_result_order}); 43 | return result.address; 44 | } 45 | 46 | //resolve using dns.resolve4 / dns.resolve6, which bypasses the system dns 47 | else if (options.dns_method === "resolve") { 48 | //we need to make a new resolver at first run because setServers doesn't work otherwise 49 | if (!resolver) resolver = new dns.Resolver(); 50 | 51 | //set custom dns servers if needed 52 | if (options.dns_servers !== dns_servers) { 53 | logging.debug("Setting custom DNS servers to: " + options.dns_servers.join(", ")); 54 | resolver.setServers(options.dns_servers); 55 | dns_servers = options.dns_servers; 56 | } 57 | 58 | if (options.dns_result_order === "verbatim" || options.dns_result_order === "ipv6first") 59 | return await resolve_with_fallback(resolve6, resolve4, hostname); 60 | else if (options.dns_result_order === "ipv4first") 61 | return await resolve_with_fallback(resolve4, resolve6, hostname); 62 | else 63 | throw new Error("Invalid result order. options.dns_result_order must be either 'ipv6first', 'ipv4first', or 'verbatim'."); 64 | } 65 | 66 | //use a custom function for dns resolution 67 | else if (typeof options.dns_method === "function") { 68 | return await options.dns_method(hostname); 69 | } 70 | 71 | throw new Error("Invalid DNS method. options.dns_method must either be 'lookup' or 'resolve'."); 72 | } 73 | 74 | //perform a dns lookup and use the cache 75 | export async function lookup_ip(hostname) { 76 | if (!is_node) { //we cannot do the dns lookup on the browser 77 | return hostname; 78 | } 79 | 80 | let ip_level = net.isIP(hostname); 81 | if (ip_level === 4 || ip_level === 6) { 82 | return hostname; //hostname is already an ip address 83 | } 84 | 85 | //remove stale entries from the cache 86 | let now = Date.now(); 87 | for (let [entry_hostname, cache_entry] of dns_cache) { 88 | let ttl = now - cache_entry.time; 89 | if (ttl > options.dns_ttl) { 90 | dns_cache.delete(entry_hostname); 91 | } 92 | } 93 | 94 | //look in the cache first before using the system resolver 95 | let cache_entry = dns_cache.get(hostname); 96 | if (cache_entry) { 97 | if (cache_entry.error) 98 | throw cache_entry.error 99 | return cache_entry.address; 100 | } 101 | 102 | //try to perform the actual dns lookup and store the result 103 | let address; 104 | try { 105 | address = await perform_lookup(hostname); 106 | logging.debug(`Domain resolved: ${hostname} -> ${address}`); 107 | dns_cache.set(hostname, {time: Date.now(), address: address}); 108 | } 109 | catch (e) { 110 | dns_cache.set(hostname, {time: Date.now(), error: e}); 111 | throw e; 112 | } 113 | 114 | return address; 115 | } 116 | 117 | //async tcp and udp socket wrappers 118 | export class NodeTCPSocket { 119 | constructor(hostname, port) { 120 | assert_on_node(); 121 | this.hostname = hostname; 122 | this.port = port; 123 | this.recv_buffer_size = 128; 124 | 125 | this.socket = null; 126 | this.paused = false; 127 | this.connected = false; 128 | this.data_queue = new AsyncQueue(this.recv_buffer_size); 129 | } 130 | 131 | async connect() { 132 | let ip = await lookup_ip(this.hostname); 133 | await new Promise((resolve, reject) => { 134 | this.socket = new net.Socket(); 135 | this.socket.setNoDelay(true); 136 | this.socket.on("connect", () => { 137 | this.connected = true; 138 | resolve(); 139 | }); 140 | this.socket.on("data", (data) => { 141 | this.data_queue.put(data); 142 | }); 143 | this.socket.on("close", (error) => { 144 | if (error && !this.connected) reject(); 145 | else this.data_queue.close(); 146 | this.socket = null; 147 | }); 148 | this.socket.on("error", (error) => { 149 | logging.warn(`tcp stream to ${this.hostname} ended with error - ${error}`); 150 | }); 151 | this.socket.on("end", () => { 152 | if (!this.socket) return; 153 | this.socket.destroy(); 154 | this.socket = null; 155 | }); 156 | this.socket.connect({ 157 | host: ip, 158 | port: this.port 159 | }); 160 | }); 161 | } 162 | 163 | async recv() { 164 | return await this.data_queue.get(); 165 | } 166 | 167 | async send(data) { 168 | await new Promise((resolve) => { 169 | this.socket.write(data, resolve); 170 | }); 171 | } 172 | 173 | async close() { 174 | if (!this.socket) return; 175 | this.socket.end(); 176 | this.socket = null; 177 | } 178 | 179 | pause() { 180 | if (this.data_queue.size >= this.data_queue.max_size) { 181 | this.socket.pause(); 182 | this.paused = true; 183 | } 184 | } 185 | resume() { 186 | if (!this.socket) return; 187 | if (this.paused) { 188 | this.socket.resume(); 189 | this.paused = false; 190 | } 191 | } 192 | } 193 | 194 | export class NodeUDPSocket { 195 | constructor(hostname, port) { 196 | assert_on_node(); 197 | this.hostname = hostname; 198 | this.port = port; 199 | 200 | this.connected = false; 201 | this.recv_buffer_size = 128; 202 | this.data_queue = new AsyncQueue(this.recv_buffer_size); 203 | } 204 | 205 | async connect() { 206 | let ip = await lookup_ip(this.hostname); 207 | let ip_level = net.isIP(ip); 208 | await new Promise((resolve, reject) => { 209 | this.socket = dgram.createSocket(ip_level === 6 ? "udp6" : "udp4"); 210 | this.socket.on("connect", () => { 211 | resolve(); 212 | }); 213 | this.socket.on("message", (data) => { 214 | this.data_queue.put(data); 215 | }); 216 | this.socket.on("error", () => { 217 | if (!this.connected) reject(); 218 | this.data_queue.close(); 219 | this.socket = null; 220 | }); 221 | this.socket.connect(this.port, ip); 222 | }); 223 | } 224 | 225 | async recv() { 226 | return await this.data_queue.get(); 227 | } 228 | 229 | async send(data) { 230 | this.socket.send(data); 231 | } 232 | 233 | async close() { 234 | if (!this.socket) return; 235 | this.socket.close(); 236 | this.socket = null; 237 | } 238 | 239 | pause() {} 240 | resume() {} 241 | } -------------------------------------------------------------------------------- /src/client/connection.mjs: -------------------------------------------------------------------------------- 1 | import * as compat from "../compat.mjs"; 2 | 3 | import { 4 | packet_classes, 5 | packet_types, 6 | stream_types, 7 | WispBuffer, 8 | WispPacket, 9 | ConnectPayload, 10 | DataPayload, 11 | ClosePayload, 12 | InfoPayload 13 | } from "../packet.mjs"; 14 | 15 | import { MOTDExtension, UDPExtension, serialize_extensions, parse_extensions } from "../extensions.mjs"; 16 | 17 | class ClientStream { 18 | constructor(hostname, port, websocket, buffer_size, stream_id, connection, stream_type) { 19 | this.hostname = hostname; 20 | this.port = port; 21 | this.ws = websocket; 22 | this.buffer_size = buffer_size; 23 | this.stream_id = stream_id; 24 | this.connection = connection; 25 | this.stream_type = stream_type; 26 | this.send_buffer = []; 27 | this.open = true; 28 | 29 | this.onopen = () => {}; 30 | this.onclose = () => {}; 31 | this.onmessage = () => {}; 32 | } 33 | 34 | send(data) { 35 | //note: udp shouldn't buffer anything 36 | if (this.buffer_size > 0 || !this.open || this.stream_type === stream_types.UDP) { 37 | //construct and send a DATA packet 38 | let packet = new WispPacket({ 39 | type: packet_types.DATA, 40 | stream_id: this.stream_id, 41 | payload: new DataPayload({ 42 | data: new WispBuffer(data) 43 | }) 44 | }); 45 | this.ws.send(packet.serialize().bytes); 46 | this.buffer_size--; 47 | } 48 | else { //server is slow, don't send data yet 49 | this.send_buffer.push(data); 50 | } 51 | } 52 | 53 | //handle receiving a CONTINUE packet 54 | continue_received(buffer_size) { 55 | this.buffer_size = buffer_size; 56 | //send buffered data now 57 | while (this.buffer_size > 0 && this.send_buffer.length > 0) { 58 | this.send(this.send_buffer.shift()); 59 | } 60 | } 61 | 62 | //construct and send a CLOSE packet 63 | close(reason = 0x01) { 64 | if (!this.open) return; 65 | let packet = new WispPacket({ 66 | type: packet_types.CLOSE, 67 | stream_id: this.stream_id, 68 | payload: new ClosePayload({ 69 | reason: reason 70 | }) 71 | }); 72 | this.ws.send(packet.serialize().bytes); 73 | this.open = false; 74 | delete this.connection.active_streams[this.stream_id]; 75 | } 76 | } 77 | 78 | export class ClientConnection { 79 | constructor(wisp_url, {wisp_version, wisp_extensions} = {}) { 80 | if (!wisp_url.endsWith("/")) { 81 | throw new TypeError("wisp endpoints must end with a trailing forward slash"); 82 | } 83 | 84 | this.wisp_url = wisp_url; 85 | this.wisp_version = wisp_version || 2; 86 | this.wisp_extensions = wisp_extensions || null; 87 | 88 | this.max_buffer_size = null; 89 | this.active_streams = {}; 90 | this.connected = false; 91 | this.connecting = false; 92 | this.next_stream_id = 1; 93 | 94 | this.server_exts = {}; 95 | this.client_exts = {}; 96 | this.info_received = false; 97 | this.server_motd = null; 98 | this.udp_enabled = true; 99 | 100 | this.onopen = () => {}; 101 | this.onclose = () => {}; 102 | this.onerror = () => {}; 103 | this.onmessage = () => {}; 104 | 105 | if (this.wisp_version === 2 && this.wisp_extensions === null) { 106 | this.add_extensions(); 107 | } 108 | 109 | this.connect_ws(); 110 | } 111 | 112 | add_extensions() { 113 | this.wisp_extensions = []; 114 | this.wisp_extensions.push(new UDPExtension({client_config: {}})); 115 | this.wisp_extensions.push(new MOTDExtension({client_config: {}})); 116 | } 117 | 118 | connect_ws() { 119 | let subprotocol = this.wisp_version === 2 ? "wisp-v2" : undefined; 120 | this.ws = new compat.WebSocket(this.wisp_url, subprotocol); 121 | this.ws.binaryType = "arraybuffer"; 122 | this.connecting = true; 123 | 124 | this.ws.onerror = () => { 125 | if (this.wisp_version === 2) { 126 | this.ws.onclose = null; 127 | this.cleanup(); 128 | this.wisp_version = 1; 129 | this.connect_ws(); 130 | return; 131 | } 132 | this.cleanup(); 133 | this.onerror(); 134 | }; 135 | this.ws.onclose = () => { 136 | this.cleanup(); 137 | this.onclose(); 138 | }; 139 | this.ws.onmessage = (event) => { 140 | this.on_ws_msg(event); 141 | if (this.connected && this.connecting) { 142 | this.connecting = false; 143 | this.onopen(); 144 | } 145 | }; 146 | } 147 | 148 | close() { 149 | this.ws.close(); 150 | } 151 | 152 | create_stream(hostname, port, type=0x01) { 153 | let stream_type = type; 154 | if (typeof stream_type === "string") 155 | stream_type = type === "udp" ? stream_types.UDP : stream_types.TCP; 156 | 157 | if (stream_type == stream_types.UDP && !this.udp_enabled) { 158 | throw new Error("udp is not enabled for this wisp connection"); 159 | } 160 | 161 | let stream_id = this.next_stream_id++; 162 | let stream = new ClientStream(hostname, port, this.ws, this.max_buffer_size, stream_id, this, stream_type); 163 | this.active_streams[stream_id] = stream; 164 | stream.open = this.connected; 165 | 166 | //construct CONNECT packet 167 | let packet = new WispPacket({ 168 | type: packet_types.CONNECT, 169 | stream_id: stream_id, 170 | payload: new ConnectPayload({ 171 | stream_type: stream_type, 172 | port: port, 173 | hostname: hostname 174 | }) 175 | }); 176 | this.ws.send(packet.serialize().bytes); 177 | return stream; 178 | } 179 | 180 | close_stream(stream, reason) { 181 | stream.onclose(reason); 182 | delete this.active_streams[stream.stream_id]; 183 | } 184 | 185 | on_ws_msg(event) { 186 | let buffer = new WispBuffer(new Uint8Array(event.data)); 187 | if (buffer.size < WispPacket.min_size) { 188 | console.warn(`wisp client warning: received a packet which is too short`); 189 | return; 190 | } 191 | let packet = WispPacket.parse_all(buffer); 192 | let stream = this.active_streams[packet.stream_id]; 193 | if (packet.stream_id === 0 && this.connecting) { 194 | if (packet.type === packet_types.CONTINUE) { 195 | this.max_buffer_size = packet.payload.buffer_remaining; 196 | this.connected = true; 197 | if (!this.info_received) { 198 | this.wisp_version = 1; 199 | } 200 | } 201 | 202 | if (packet.type === packet_types.INFO && this.wisp_version === 2) { 203 | let server_extensions = parse_extensions(packet.payload.extensions, this.wisp_extensions, "server"); 204 | for (let server_ext of server_extensions) { 205 | for (let client_ext of this.wisp_extensions) { 206 | if (server_ext.id === client_ext.id) { 207 | this.server_exts[server_ext.id] = server_ext; 208 | this.client_exts[client_ext.id] = client_ext; 209 | } 210 | } 211 | } 212 | 213 | this.info_received = true; 214 | this.server_motd = this.server_exts[MOTDExtension.id]?.payload?.message; 215 | this.udp_enabled = !!this.server_exts[UDPExtension.id]; 216 | 217 | let ext_buffer = serialize_extensions(this.wisp_extensions); 218 | let info_packet = new WispPacket({ 219 | type: InfoPayload.type, 220 | stream_id: 0, 221 | payload: new InfoPayload({ 222 | major_ver: this.wisp_version, 223 | minor_ver: 0, 224 | extensions: ext_buffer 225 | }) 226 | }); 227 | this.ws.send(info_packet.serialize().bytes); 228 | } 229 | return; 230 | } 231 | 232 | if (typeof stream === "undefined") { 233 | console.warn(`wisp client warning: received a ${packet_classes[packet.type].name} packet for a stream which doesn't exist`); 234 | return; 235 | } 236 | 237 | if (packet.type === packet_types.DATA) { 238 | stream.onmessage(packet.payload_bytes.bytes); 239 | } 240 | 241 | else if (packet.type === packet_types.CONTINUE) { //other CONTINUE packets 242 | stream.continue_received(packet.payload.buffer_remaining); 243 | } 244 | 245 | else if (packet.type === packet_types.CLOSE) { 246 | this.close_stream(stream, packet.payload.reason); 247 | } 248 | 249 | else { 250 | console.warn(`wisp client warning: received an invalid packet of type ${packet.type}`); 251 | } 252 | } 253 | 254 | cleanup() { 255 | this.connected = false; 256 | this.connecting = false; 257 | for (let stream_id of Object.keys(this.active_streams)) { 258 | this.close_stream(this.active_streams[stream_id], 0x03); 259 | } 260 | } 261 | } 262 | 263 | -------------------------------------------------------------------------------- /src/server/connection.mjs: -------------------------------------------------------------------------------- 1 | import * as logging from "../logging.mjs"; 2 | import * as filter from "./filter.mjs"; 3 | import { AsyncQueue, AsyncWebSocket, get_conn_id } from "../websocket.mjs"; 4 | import { NodeTCPSocket, NodeUDPSocket } from "./net.mjs"; 5 | import { 6 | WispBuffer, 7 | WispPacket, 8 | ContinuePayload, 9 | ClosePayload, 10 | ConnectPayload, 11 | DataPayload, 12 | InfoPayload, 13 | stream_types, 14 | close_reasons 15 | } from "../packet.mjs"; 16 | import { options } from "./options.mjs"; 17 | import { MOTDExtension, UDPExtension, serialize_extensions, parse_extensions } from "../extensions.mjs"; 18 | 19 | export class HandshakeError extends Error {} 20 | 21 | export class ServerStream { 22 | static buffer_size = 128; 23 | 24 | constructor(stream_id, conn, socket) { 25 | this.stream_id = stream_id; 26 | this.conn = conn; 27 | this.socket = socket; 28 | this.send_buffer = new AsyncQueue(ServerStream.buffer_size); 29 | this.packets_sent = 0; 30 | } 31 | 32 | async setup() { 33 | await this.socket.connect(); 34 | 35 | //start the proxy tasks in the background 36 | this.tcp_to_ws().catch((error) => { 37 | logging.error(`(${this.conn.conn_id}) a tcp/udp to ws task encountered an error - ${error}`); 38 | this.close(); 39 | }); 40 | this.ws_to_tcp().catch((error) => { 41 | logging.error(`(${this.conn.conn_id}) a ws to tcp/udp task encountered an error - ${error}`); 42 | this.close(); 43 | }); 44 | } 45 | 46 | async tcp_to_ws() { 47 | while (true) { 48 | let data = await this.socket.recv(); 49 | if (data == null) { 50 | break; 51 | } 52 | 53 | this.socket.pause(); 54 | let packet = new WispPacket({ 55 | type: DataPayload.type, 56 | stream_id: this.stream_id, 57 | payload: new DataPayload({ 58 | data: new WispBuffer(new Uint8Array(data)) 59 | }) 60 | }); 61 | await this.conn.ws.send(packet); 62 | this.socket.resume(); 63 | } 64 | await this.conn.close_stream(this.stream_id, close_reasons.Voluntary); 65 | } 66 | 67 | async ws_to_tcp() { 68 | while (true) { 69 | let data = await this.send_buffer.get(); 70 | if (data == null) { 71 | break; //stream closed 72 | } 73 | await this.socket.send(data); 74 | 75 | this.packets_sent++; 76 | if (this.packets_sent % (ServerStream.buffer_size / 2) !== 0) { 77 | continue; 78 | } 79 | let packet = new WispPacket({ 80 | type: ContinuePayload.type, 81 | stream_id: this.stream_id, 82 | payload: new ContinuePayload({ 83 | buffer_remaining: ServerStream.buffer_size - this.send_buffer.size 84 | }) 85 | }); 86 | this.conn.ws.send(packet); 87 | } 88 | await this.close(); 89 | } 90 | 91 | async close(reason = null) { 92 | this.send_buffer.close(); 93 | this.socket.close(); 94 | if (reason == null) return; 95 | 96 | let packet = new WispPacket({ 97 | type: ClosePayload.type, 98 | stream_id: this.stream_id, 99 | payload: new ClosePayload({ 100 | reason: reason 101 | }) 102 | }); 103 | await this.conn.ws.send(packet); 104 | } 105 | 106 | async put_data(data) { 107 | await this.send_buffer.put(data); 108 | } 109 | } 110 | 111 | export class ServerConnection { 112 | constructor(ws, path, {TCPSocket, UDPSocket, ping_interval, wisp_version, wisp_extensions} = {}) { 113 | this.ws = new AsyncWebSocket(ws); 114 | this.path = path; 115 | this.TCPSocket = TCPSocket || NodeTCPSocket; 116 | this.UDPSocket = UDPSocket || NodeUDPSocket; 117 | this.ping_interval = ping_interval || 30; 118 | this.wisp_version = wisp_version || options.wisp_version; 119 | this.wisp_extensions = wisp_extensions || null; 120 | 121 | this.ping_task = null; 122 | this.streams = {}; 123 | this.conn_id = get_conn_id(); 124 | 125 | this.server_exts = {}; 126 | this.client_exts = {}; 127 | 128 | if (this.wisp_version === 2 && this.wisp_extensions === null) { 129 | this.add_extensions(); 130 | } 131 | } 132 | 133 | add_extensions() { 134 | this.wisp_extensions = []; 135 | if (options.allow_udp_streams) 136 | this.wisp_extensions.push(new UDPExtension({server_config: {}})); 137 | if (options.wisp_motd) 138 | this.wisp_extensions.push(new MOTDExtension({server_config: { 139 | message: options.wisp_motd 140 | }})); 141 | } 142 | 143 | async setup() { 144 | logging.info(`setting up new wisp v${this.wisp_version} connection with id ${this.conn_id}`); 145 | 146 | await this.ws.connect(); 147 | if (this.wisp_version == 2) { 148 | await this.setup_wisp_v2() 149 | } 150 | 151 | //send initial continue packet 152 | let continue_packet = new WispPacket({ 153 | type: ContinuePayload.type, 154 | stream_id: 0, 155 | payload: new ContinuePayload({ 156 | buffer_remaining: ServerStream.buffer_size 157 | }) 158 | }); 159 | this.ws.send(continue_packet); 160 | 161 | if (typeof this.ws.ws.ping === "function") { 162 | this.ping_task = setInterval(() => { 163 | logging.debug(`(${this.conn_id}) sending websocket ping`); 164 | this.ws.ws.ping(); 165 | }, this.ping_interval * 1000); 166 | } 167 | } 168 | 169 | async setup_wisp_v2() { 170 | //send initial info packet for wisp v2 171 | let ext_buffer = serialize_extensions(this.wisp_extensions); 172 | let info_packet = new WispPacket({ 173 | type: InfoPayload.type, 174 | stream_id: 0, 175 | payload: new InfoPayload({ 176 | major_ver: this.wisp_version, 177 | minor_ver: 0, 178 | extensions: ext_buffer 179 | }) 180 | }); 181 | this.ws.send(info_packet); 182 | 183 | //wait for the client's info packet 184 | let data = await this.ws.recv(); 185 | if (data == null) { 186 | logging.warn(`(${this.conn_id}) handshake error: ws closed before handshake complete`); 187 | await this.cleanup(); 188 | throw new HandshakeError(); 189 | } 190 | let buffer = new WispBuffer(new Uint8Array(data)); 191 | let packet = WispPacket.parse_all(buffer); 192 | 193 | if (packet.type !== InfoPayload.type) { 194 | logging.warn(`(${this.conn_id}) handshake error: unexpected packet of type ${packet.type}`); 195 | await this.cleanup(); 196 | throw new HandshakeError(); 197 | } 198 | 199 | //figure out the common extensions 200 | let client_extensions = parse_extensions(packet.payload.extensions, this.wisp_extensions, "client"); 201 | for (let client_ext of client_extensions) { 202 | for (let server_ext of this.wisp_extensions) { 203 | if (server_ext.id === client_ext.id) { 204 | this.server_exts[server_ext.id] = server_ext; 205 | this.client_exts[client_ext.id] = client_ext; 206 | } 207 | } 208 | } 209 | } 210 | 211 | create_stream(stream_id, type, hostname, port) { 212 | let SocketImpl = type === stream_types.TCP ? this.TCPSocket : this.UDPSocket; 213 | let socket = new SocketImpl(hostname, port); 214 | let stream = new ServerStream(stream_id, this, socket); 215 | this.streams[stream_id] = stream; 216 | 217 | //start connecting to the destination server in the background 218 | (async () => { 219 | let close_reason = await filter.is_stream_allowed(this, type, hostname, port); 220 | if (close_reason) { 221 | logging.warn(`(${this.conn_id}) refusing to create a stream to ${hostname}:${port}`); 222 | await this.close_stream(stream_id, close_reason, true); 223 | return; 224 | } 225 | try { 226 | await stream.setup(); 227 | } 228 | catch (error) { 229 | logging.warn(`(${this.conn_id}) creating a stream to ${hostname}:${port} failed - ${error}`); 230 | await this.close_stream(stream_id, close_reasons.NetworkError); 231 | } 232 | })(); 233 | } 234 | 235 | async close_stream(stream_id, reason = null, quiet = false) { 236 | let stream = this.streams[stream_id]; 237 | if (stream == null) { 238 | return; 239 | } 240 | if (reason && !quiet) { 241 | logging.info(`(${this.conn_id}) closing stream to ${stream.socket.hostname} for reason ${reason}`); 242 | } 243 | await stream.close(reason); 244 | delete this.streams[stream_id]; 245 | } 246 | 247 | route_packet(buffer) { 248 | let packet = WispPacket.parse_all(buffer); 249 | let stream = this.streams[packet.stream_id]; 250 | 251 | if (stream == null && packet.type == DataPayload.type) { 252 | logging.warn(`(${this.conn_id}) received a DATA packet for a stream which doesn't exist`); 253 | return; 254 | } 255 | 256 | if (packet.type === ConnectPayload.type) { 257 | let type_info = packet.payload.stream_type === stream_types.TCP ? "TCP" : "UDP"; 258 | logging.info(`(${this.conn_id}) opening new ${type_info} stream to ${packet.payload.hostname}:${packet.payload.port}`); 259 | this.create_stream( 260 | packet.stream_id, 261 | packet.payload.stream_type, 262 | packet.payload.hostname.trim(), 263 | packet.payload.port 264 | ) 265 | } 266 | 267 | else if (packet.type === DataPayload.type) { 268 | stream.put_data(packet.payload.data.bytes); 269 | } 270 | 271 | else if (packet.type == ContinuePayload.type) { 272 | logging.warn(`(${this.conn_id}) client sent a CONTINUE packet, this should never be possible`); 273 | } 274 | 275 | else if (packet.type == ClosePayload.type) { 276 | this.close_stream(packet.stream_id, packet.reason); 277 | } 278 | } 279 | 280 | async run() { 281 | while (true) { 282 | let data; 283 | data = await this.ws.recv(); 284 | if (data == null) { 285 | break; //websocket closed 286 | } 287 | if (typeof data === "string") { 288 | logging.warn(`(${this.conn_id}) routing a packet failed - unexpected ws text frame`); 289 | continue; 290 | } 291 | 292 | try { 293 | //note: data is an arraybuffer so the uint8array constructor does not copy 294 | this.route_packet(new WispBuffer(new Uint8Array(data))); 295 | } 296 | catch (error) { 297 | logging.warn(`(${this.conn_id}) routing a packet failed - ${error}`); 298 | } 299 | } 300 | 301 | await this.cleanup(); 302 | } 303 | 304 | async cleanup() { 305 | //clean up all streams when the websocket is closed 306 | for (let stream_id of Object.keys(this.streams)) { 307 | await this.close_stream(stream_id); 308 | } 309 | clearInterval(this.ping_task); 310 | logging.info(`(${this.conn_id}) wisp connection closed`); 311 | this.ws.close(); 312 | } 313 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JavaScript Wisp Implementation 2 | 3 | This is an implementation of a [Wisp](https://github.com/mercuryWorkshop/wisp-protocol) client and server, written in Javascript for use in NodeJS and in the browser. 4 | 5 | ## Features: 6 | - Complete Wisp client and server implementations 7 | - Supports Wisp v2 and v1 8 | - APIs available for client and server 9 | - Highly configurable 10 | - Supports NodeJS and the browser 11 | 12 | ### Library Entrypoints: 13 | - `@mercuryworkshop/wisp-js/client` - Only contains the client code. 14 | - `@mercuryworkshop/wisp-js/server` - Contains the server code, and the logging module. 15 | - `@mercuryworkshop/wisp-js` - Contains the server, client, and logging code. 16 | 17 | All of these entrypoints support being imported as either a CommonJS or ES6 module. 18 | 19 | ## Server CLI: 20 | THere is a CLI interface available for the Wisp server, and it can be used by running: 21 | ``` 22 | $ npm i @mercuryworkshop/wisp-js 23 | added 6 packages in 2s 24 | $ npx wisp-js-server --help 25 | Usage: wisp-js-server [options] 26 | 27 | A Wisp server implementation written in Javascript. (v0.4.0) 28 | 29 | Options: 30 | -V, --version output the version number 31 | -H, --host The hostname the server will listen on. (default: "127.0.0.1") 32 | -P, --port The port number to run the server on. (default: 5001) 33 | -L, --logging The log level to use. This is either DEBUG, INFO, WARN, ERROR, or NONE. 34 | (default: "INFO") 35 | -S, --static The directory to serve static files from. (optional) 36 | -C, --config The path to your Wisp server config file. This is the same format as 37 | `wisp.options` in the API. (optional) 38 | -O, --options A JSON string to set the Wisp config without using a file. (optional) 39 | -h, --help display help for command 40 | ``` 41 | You may also clone this repository and run `npm run server_cli -- --help`. 42 | 43 | The config file is a JSON file with the same entries as the [global server config](https://github.com/MercuryWorkshop/wisp-client-js/?tab=readme-ov-file#changing-server-settings) in the API. 44 | 45 | ## Client API: 46 | 47 | ### Importing the Client Library: 48 | To use the library as an ES6 module, either in Node or using a bundler for the browser, include the following import: 49 | ```js 50 | import { client as wisp } from "@mercuryworkshop/wisp-js/client"; 51 | ``` 52 | 53 | To use it in Node with CommonJS: 54 | ```js 55 | const { client: wisp } = require("@mercuryworkshop/wisp-js/client"); 56 | ``` 57 | 58 | If you are not using a bundler, you may import the files in the dist folder of the package. The `wisp-client.mjs` file is an ES6 module that has the same entrypoint as the example above. The `wisp-client.js` file is a regular JS file that produce a global variable named `wisp_client`, which contains all of the exported modules. 59 | 60 | ### Connecting to a Wisp Server: 61 | You can create a new Wisp connection by creating a new `ClientConnection` object. The only argument to the constructor is the URL of the Wisp websocket server. Use the `open` event to know when the Wisp connection is ready. 62 | ```js 63 | import { client as wisp } from "@mercuryworkshop/wisp-js/client"; 64 | 65 | let conn = new wisp.ClientConnection("wss://example.com/wisp/"); 66 | conn.onopen = () => { 67 | console.log("wisp connection is ready!"); 68 | }; 69 | conn.onclose = () => { 70 | console.log("wisp connection closed"); 71 | }; 72 | conn.onerror = () => { 73 | console.log("wisp connection error"); 74 | }; 75 | ``` 76 | 77 | You can close the Wisp connection with `conn.close()`. 78 | 79 | ### Creating New Streams: 80 | Once you have your `WispConnection` object, and you have waited for the connection to be established, you can use the `WispConnection.create_stream` method to create new streams. The two arguments to this function are the hostname and port of the new stream, and a `WispStream` object will be returned. You can also pass a third argument to `create_stream`, which is the type of the stream, and it can be either `"tcp"` (the default) or `"udp"`. 81 | 82 | For receiving incoming messages, use the `onmessage` callback on the `WispStream` object. The returned data will always be a `Uint8Array`. The `onclose` callback can be used to know when the stream is closed. 83 | 84 | You can use `stream.send` to send data to the stream, and it must take a `Uint8Array` as the argument. Newly created streams are available for writing immediately, so you don't have to worry about waiting to send your data. 85 | ```js 86 | let stream = conn.create_stream("www.google.com", 80); 87 | stream.onmessage = (data) => { 88 | let text = new TextDecoder().decode(data); 89 | console.log(text); 90 | }; 91 | stream.onclose = (reason) => { 92 | console.log("stream closed for reason: " + reason); 93 | }; 94 | 95 | let payload = "GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n"; 96 | stream.send(new TextEncoder().encode(payload)); 97 | ``` 98 | 99 | ### Using the WebSocket Polyfill: 100 | The `polyfill.js` file provides an API similar to the regular [DOM WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket). Instead of creating new `WebSocket` objects, create `WispWebSocket` objects. Make sure the URL ends with the hostname and port you want to connect to. If you have code that uses the older wsproxy protocol, you can use this polyfill to provide Wisp support easily. 101 | ```js 102 | import { client as wisp } from "@mercuryworkshop/wisp-js/client"; 103 | 104 | let ws = new wisp.WispWebSocket("wss://example.com/ws/alicesworld.tech:80"); 105 | ws.binaryType = "arraybuffer"; 106 | ws.addEventListener("open", () => { 107 | let payload = "GET / HTTP/1.1\r\nHost: alicesworld.tech\r\nConnection: keepalive\r\n\r\n"; 108 | ws.send(payload); 109 | }); 110 | ws.addEventListener("message", (event) => { 111 | let text = new TextDecoder().decode(event.data); 112 | console.log("message from stream 1: ", text.slice(0, 128)); 113 | }); 114 | ``` 115 | 116 | The `wisp_client._wisp_connections` object will be used to manage the active Wisp connections. This object is able to store multiple active Wisp connections, identified by the websocket URL. 117 | 118 | ### Client Options: 119 | 120 | `ClientConnection` and `WispWebSocket` both accept an additional argument which specifies additional options for the Wisp connection. 121 | 122 | The following options are accepted: 123 | - `wisp_version` - Sets the Wisp version to use for the client (either `1` or `2`). If Wisp v2 is used, Wisp v1 connections will still be accepted. Defaults to `2`. 124 | - `wisp_extensions` - Specifies custom Wisp v2 extensions to be used on the client. 125 | 126 | For example: 127 | ```js 128 | let conn = new wisp.ClientConnection(ws_url, {wisp_version: 1}); 129 | 130 | let ws = new wisp.WispWebSocket(ws_url + "cloudflare.com:80", null, {wisp_version: 1}); 131 | ``` 132 | 133 | ## Server API: 134 | ### Importing the Server Library: 135 | To use the library as an ES6 module, either in Node or using a bundler for the browser, include the following import: 136 | ```js 137 | import { server as wisp } from "@mercuryworkshop/wisp-js/server"; 138 | ``` 139 | 140 | To use it in Node with CommonJS: 141 | ```js 142 | const { server: wisp } = require("@mercuryworkshop/wisp-js/client"); 143 | ``` 144 | 145 | This is designed to be a drop-in replacement for [wisp-server-node](https://github.com/MercuryWorkshop/wisp-server-node). You can replace your old import with one of the above examples, and your application will still work in the same way. 146 | 147 | ### Basic Example: 148 | This example uses the `node:http` module as a basic web server. It accepts new Wisp connections from incoming websockets. 149 | ```js 150 | import { server as wisp } from "@mercuryworkshop/wisp-js/server"; 151 | import http from "node:http"; 152 | 153 | const server = http.createServer((req, res) => { 154 | res.writeHead(200, { "Content-Type": "text/plain" }); 155 | res.end("wisp server js rewrite"); 156 | }); 157 | 158 | server.on("upgrade", (req, socket, head) => { 159 | wisp.routeRequest(req, socket, head); 160 | }); 161 | 162 | server.on("listening", () => { 163 | console.log("HTTP server listening"); 164 | }); 165 | 166 | server.listen(5001, "127.0.0.1"); 167 | ``` 168 | 169 | ### Example With Express: 170 | ```js 171 | import { server as wisp } from "@mercuryworkshop/wisp-js/server"; 172 | import express from "express"; 173 | import morgan from "morgan"; 174 | 175 | const app = express(); 176 | const port = process.env.PORT || 5001; 177 | 178 | app.use(morgan("combined")); 179 | app.use(express.static("./")); 180 | 181 | const server = app.listen(port, () => { 182 | console.log("Listening on port: ", port) 183 | }); 184 | 185 | server.on("upgrade", (request, socket, head) => { 186 | wisp.routeRequest(request, socket, head); 187 | }); 188 | ``` 189 | 190 | ### Change the Log Level: 191 | By default, all info messages are shown. You can change this by importing `logging` from the module, and calling `logging.set_level` to set it to one of the following values: 192 | - `logging.DEBUG` 193 | - `logging.INFO` (default) 194 | - `logging.WARN` 195 | - `logging.ERROR` 196 | - `logging.NONE` 197 | 198 | ```js 199 | import { server as wisp, logging } from "@mercuryworkshop/wisp-js/server"; 200 | 201 | logging.set_level(logging.DEBUG); 202 | ``` 203 | 204 | ### Changing Server Settings: 205 | To change settings globally for the Wisp server, you can use the `wisp.options` object. Here is a list of all of the available settings: 206 | 207 | **Blacklist / Whitelist Options:** 208 | - `options.hostname_blacklist` - An array of regex objects to match against the destination server. Any matches will be blocked. 209 | - `options.hostname_whitelist` - Same as `hostname_blacklist`, but only matches will be allowed through, and setting this will supersede `hostname_blacklist`. 210 | - `options.port_blacklist` - An array of port numbers or ranges to block on the destination server. Specific ports are expressed as a single number, and ranges consist of a two element array containing the start and end. For example `80` and `[3000, 4000]` are both valid entries in this array. 211 | - `options.port_whitelist` - Same as `port_whitelist`, but only matches will be allowed through, and setting this will supersede `port_blacklist`. 212 | 213 | **Stream Restrictions:** 214 | - `options.stream_limit_per_host` - The maximum number of streams that may be open to a single hostname, per connection. Defaults to no limit. 215 | - `options.stream_limit_total` - The total number of streams that may be open to all hosts combined, per connection. Defaults to no limit. 216 | - `options.allow_udp_streams` - If this is `false`, UDP streams will be blocked. Defaults to `true`. 217 | - `options.allow_tcp_streams` - If this is `false`, TCP streams will be blocked. Defaults to `true`. 218 | 219 | **IP Restrictions:** 220 | - `options.allow_direct_ip` - Allow connections directly to IP addresses, which bypasses the server-side DNS resolution. Turning this off allows the server administrator to enforce a block list more effectively. Defaults to `true`. 221 | - `options.allow_private_ips` - Allow connections to private IP addresses. Defaults to `false`. 222 | - `options.allow_loopback_ips` - Allow connections to the server's localhost (127.0.0.1) and other loopback IPs. Defaults to `false`. 223 | - `options.parse_real_ip` - Parse the client's real IP from the `X-Forwarded-For` and `X-Real-IP` headers. Defaults to `true`. 224 | - `options.parse_real_ip_from` - A list of IP addresses to allow parsing the real IP from. Defaults to `["127.0.0.1"]`. 225 | 226 | **DNS Settings:** 227 | - `options.dns_ttl` - The time to live for cached DNS responses, in seconds. Defaults to `120` seconds. 228 | - `options.dns_method` - The method to use for DNS resolution. This is either `"lookup"`, which uses the system DNS, or `"resolve"`, which uses the Node `dns.resolve` functions. This may also be a custom async function, which takes the hostname as its only argument and returns the resolved IP address. Defaults to `"lookup"`. 229 | - `options.dns_servers` - A [list of strings containing IP addresses](https://nodejs.org/api/dns.html#dnspromisessetserversservers) for custom DNS servers. This is only used if `dns_method` is set to `"resolve"`. By default, this is unset, and DNS queries will use the system DNS servers. 230 | - `options.dns_result_order` - Controls whether or not IPv4 or IPv6 addresses are prioritized. This can be either `"ipv4first"`, `"ipv6first"`, or `"verbatim"`. `"verbatim"` uses the original order that the system DNS returns the results in, and only has special meaning if the DNS method is `"lookup"`. If the DNS method is `"resolve"`, `"verbatim"` is treated the same as `"ipv6first"`. Defaults to `"verbatim"`. 231 | 232 | **Wisp V2 Options:** 233 | - `options.wisp_version` - Sets the Wisp version to use for the server (either `1` or `2`). If Wisp v2 is used, Wisp v1 connections will still be accepted. Defaults to `2`. 234 | - `options.wisp_motd` - Sets the MOTD for the server if Wisp v2 is used. Defaults to `null`. 235 | 236 | For example: 237 | ```js 238 | wisp.options.port_whitelist = [ 239 | [5000, 6000], 240 | 80, 241 | 443 242 | ]; 243 | wisp.options.hostname_blacklist = [ 244 | /google\.com/, 245 | /reddit\.com/, 246 | ]; 247 | ``` 248 | ```js 249 | wisp.options.dns_method = "resolve"; 250 | wisp.options.dns_servers = ["1.1.1.3", "1.0.0.3"]; 251 | wisp.options.dns_result_order = "ipv4first"; 252 | ``` 253 | 254 | ## Copyright: 255 | This library is licensed under the GNU AGPL v3. 256 | 257 | ### Copyright Notice: 258 | ``` 259 | wisp-js: a Wisp client implementation written in JavaScript 260 | Copyright (C) 2024 Mercury Workshop 261 | 262 | This program is free software: you can redistribute it and/or modify 263 | it under the terms of the GNU Affero General Public License as published 264 | by the Free Software Foundation, either version 3 of the License, or 265 | (at your option) any later version. 266 | 267 | This program is distributed in the hope that it will be useful, 268 | but WITHOUT ANY WARRANTY; without even the implied warranty of 269 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 270 | GNU Affero General Public License for more details. 271 | 272 | You should have received a copy of the GNU Affero General Public License 273 | along with this program. If not, see . 274 | ``` -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------