From 66fdd5ff2887d8a40ea45dc054d9bf8bc9a64645 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20=C5=BD=C3=A1ra?= Date: Sun, 20 Sep 2020 18:39:42 +0200 Subject: [PATCH] support for password protection --- index.js | 13 ++++++++++--- package.json | 2 +- queue.js | 4 +++- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index fedc959..27bd204 100644 --- a/index.js +++ b/index.js @@ -3,7 +3,11 @@ const log = require("./log.js").log; const Queue = require("./queue").Queue; -function initConnection(request) { +function escape(str) { + return str.replace(/(['"\\])/g, "\\$1"); +} + +function initConnection(request, passwords = {}) { let ws = request.accept(); log("ws connection accepted from origin", request.origin); @@ -23,6 +27,9 @@ function initConnection(request) { ws.send(JSON.stringify(data)); }); + let password = passwords[`${host}:${port}`]; + password && queue.add(`password "${escape(password)}"`); + // data going into the response parser ws.on("message", message => { log("ws -->", message.utf8Data); @@ -52,7 +59,7 @@ exports.logging = function(enabled) { log.enabled = enabled; } -exports.ws2mpd = function(httpServer, requestValidator) { +exports.ws2mpd = function(httpServer, requestValidator, passwords) { function ready() { log("ws2mpd attached to a http server", httpServer.address()); } (httpServer.listening ? ready() : httpServer.on("listening", ready)); @@ -66,6 +73,6 @@ exports.ws2mpd = function(httpServer, requestValidator) { log("rejecting connection from origin", request.origin); return request.reject(); } - initConnection(request); + initConnection(request, passwords); }); } diff --git a/package.json b/package.json index d00ac7c..ac90c32 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ws2mpd", - "version": "2.2.1", + "version": "2.3.0", "description": "", "main": "index.js", "scripts": { diff --git a/queue.js b/queue.js index 27bfb96..66e38eb 100644 --- a/queue.js +++ b/queue.js @@ -49,6 +49,7 @@ class Normal extends Response { } } +class Password extends Normal {} class Idle extends Normal {} class Welcome extends Response { @@ -144,7 +145,7 @@ exports.Queue = class extends EventEmitter { this._current = cmd; cmd.on("done", data => { - this.emit("response", data); + if (ctor != Password) { this.emit("response", data); } // do not pass password check result back this._current = null; this._process(); }); @@ -153,6 +154,7 @@ exports.Queue = class extends EventEmitter { function getCtor(command) { switch (true) { + case command.startsWith("password"): return Password; case command.startsWith("idle"): return Idle; case command.startsWith("albumart") || command.startsWith("readpicture"): return Binary; default: return Normal;