Skip to content

Commit

Permalink
fix: validate base URL before passing it to websocket constructor
Browse files Browse the repository at this point in the history
Closes #316
  • Loading branch information
zachowj committed Dec 31, 2020
1 parent f4e4ce6 commit 94d603d
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 10 deletions.
9 changes: 0 additions & 9 deletions lib/home-assistant.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,6 @@ class HomeAssistant {
}

async connect() {
if (!this.config.baseUrl) {
throw new Error('Base URL needs to be set');
}
if (!/^https?:\/\//.test(this.config.baseUrl)) {
throw new Error(
'Invalid Base Url. Needs to start with http:// or https://'
);
}

await this.websocket.connect();
}

Expand Down
28 changes: 27 additions & 1 deletion nodes/config-server/config-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const bonjour = require('bonjour')();
const flatten = require('flat');
const selectn = require('selectn');
const uniq = require('lodash.uniq');
const url = require('url');

const BaseNode = require('../../lib/base-node');
const HomeAssistant = require('../../lib/home-assistant');
Expand Down Expand Up @@ -184,8 +185,15 @@ module.exports = function (RED) {
}

async init() {
const baseUrl = this.credentials.host.trim();
const errorMessage = validateBaseUrl(baseUrl);
if (errorMessage) {
this.node.error(RED._(errorMessage, { url: baseUrl }));
return;
}

this.homeAssistant = new HomeAssistant({
baseUrl: this.credentials.host,
baseUrl,
apiPass: this.credentials.access_token,
legacy: this.nodeConfig.legacy,
rejectUnauthorizedCerts: this.nodeConfig
Expand Down Expand Up @@ -328,4 +336,22 @@ module.exports = function (RED) {
access_token: { type: 'text' },
},
});

function validateBaseUrl(baseUrl) {
if (!baseUrl) {
return 'config-server.errors.empty_base_url';
}

let parsedUrl;
try {
// eslint-disable-next-line no-new
parsedUrl = new url.URL(baseUrl);
} catch (e) {
return 'config-server.errors.invalid_base_url';
}

if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
return 'config-server.errors.invalid_protocol';
}
}
};
9 changes: 9 additions & 0 deletions nodes/config-server/locales/en-US/config-server.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"config-server": {
"errors": {
"empty_base_url": "Home Assistant base URL needs to be set",
"invalid_base_url": "Invalid base URL for Home Assistant: [__url__]",
"invalid_protocol": "Home Assistnat base URL needs to begin with http:// or https://"
}
}
}

0 comments on commit 94d603d

Please sign in to comment.