Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/slow-seas-lead.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@ecoflow-api/rest-client": patch
---

add host URL validation
33 changes: 33 additions & 0 deletions packages/rest-client/src/lib/RestClient.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { describe, expect, it } from "@jest/globals";
import { RestClient } from "./RestClient";

describe("RestClient", () => {
const createClient = (host: string) =>
new RestClient({
accessKey: "test-access-key",
secretKey: "test-secret-key",
host,
});

it("should construct successfully with a valid https host", () => {
expect(() => createClient("https://api-e.ecoflow.com")).not.toThrow();
});

it("should construct successfully with a valid http host", () => {
expect(() => createClient("http://localhost:3000")).not.toThrow();
});

it("should throw an error with an invalid host URL", () => {
expect(() => createClient("invalid-url")).toThrow("Invalid host URL");
});

it("should throw an error with an invalid protocol", () => {
expect(() => createClient("sftp://api.ecoflow.com")).toThrow(
"Invalid host protocol: http or https expected",
);
});

it("should throw an error with an empty host", () => {
expect(() => createClient("")).toThrow("Invalid host URL");
});
});
9 changes: 9 additions & 0 deletions packages/rest-client/src/lib/RestClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,15 @@ export class RestClient {
* @constructor
*/
constructor(opts: RestClientOptions) {
const parsed = URL.parse(opts.host);
if (!parsed) {
throw new Error(`Invalid host URL`);
}

if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
throw new Error(`Invalid host protocol: http or https expected`);
}

const generateUrl = (path: string) => `${opts.host}${path}`;

this.requestHandler = new RequestHandler(
Expand Down