// Import Node's built-in test tools. const test = require("node:test"); const assert = require("node:assert/strict"); // Import the functions we want to test. const { isPrivateIp, validatePublicUrl, } = require("../src/services/urlSecurityService"); // --------------------------------------------------------- // isPrivateIp() tests // --------------------------------------------------------- test("blocks IPv4 loopback addresses", () => { assert.equal(isPrivateIp("127.0.0.1"), true); }); test("blocks private 10.x.x.x addresses", () => { assert.equal(isPrivateIp("10.0.0.1"), true); }); test("blocks private 172.16.x.x addresses", () => { assert.equal(isPrivateIp("172.16.0.1"), true); }); test("blocks private 192.168.x.x addresses", () => { assert.equal(isPrivateIp("192.168.1.1"), true); }); test("blocks link-local addresses", () => { assert.equal(isPrivateIp("169.254.1.1"), true); }); test("blocks IPv6 loopback", () => { assert.equal(isPrivateIp("::1"), true); }); test("allows a public IPv4 address", () => { assert.equal(isPrivateIp("1.1.1.1"), false); }); test("blocks malformed IP addresses", () => { assert.equal(isPrivateIp("not-an-ip"), true); }); // --------------------------------------------------------- // validatePublicUrl() tests // --------------------------------------------------------- test("accepts a public HTTP URL using a public IP", async () => { const result = await validatePublicUrl("http://1.1.1.1"); assert.equal(result.protocol, "http:"); assert.equal(result.hostname, "1.1.1.1"); }); test("accepts a public HTTPS URL using a public IP", async () => { const result = await validatePublicUrl("https://1.1.1.1"); assert.equal(result.protocol, "https:"); assert.equal(result.hostname, "1.1.1.1"); }); test("rejects localhost", async () => { await assert.rejects( validatePublicUrl("http://localhost"), /Local and private network addresses are not allowed/ ); }); test("rejects localhost subdomains", async () => { await assert.rejects( validatePublicUrl("http://test.localhost"), /Local and private network addresses are not allowed/ ); }); test("rejects private IP addresses", async () => { await assert.rejects( validatePublicUrl("http://192.168.1.1"), /Local and private network addresses are not allowed/ ); }); test("rejects unsupported protocols", async () => { await assert.rejects( validatePublicUrl("ftp://example.com"), /Only HTTP and HTTPS URLs are allowed/ ); }); test("rejects URLs containing credentials", async () => { await assert.rejects( validatePublicUrl("https://username:password@example.com"), /URLs containing usernames or passwords are not allowed/ ); }); test("rejects nonstandard ports", async () => { await assert.rejects( validatePublicUrl("https://example.com:8080"), /Only ports 80 and 443 are allowed/ ); }); test("rejects malformed URLs", async () => { await assert.rejects( validatePublicUrl("this is not a URL"), /Enter a valid URL/ ); });