Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Redirect checking being applied to all URIs #69

Merged
merged 1 commit into from
Oct 30, 2024
Merged
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
121 changes: 60 additions & 61 deletions pages/api/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { db } from "../../utils/firebase";
import CryptoJS from "crypto-js";
import { StatusCodes } from "http-status-codes";

const regex = /^(https?|ftp|magnet):(?:\/\/[^\s/$.?#].[^\s]*|[^\s]*)$/;
const regex = /^(?:(http)s?|ftp|magnet):(?:\/\/[^\s/$.?#].[^\s]*|[^\s]*)$/;

const slugRegex = /^[a-z0-9](-?[a-z0-9])*$/;

Expand Down Expand Up @@ -91,7 +91,8 @@ export default async function handler(req, res) {
}

const collectionName =
process.env.NODE_ENV === "production" ? "links" : "testLinks";
process.env.NODE_ENV === "production" ? "links" : "testLinks",
URI = regex.exec(link);

// check if link is valid
if (link.length < 1) {
Expand All @@ -100,7 +101,7 @@ export default async function handler(req, res) {
.json({ slug, message: "You entered an invalid link" });
}

if (!regex.test(link)) {
if (URI === null) {
return res.status(StatusCodes.BAD_REQUEST).json({
slug,
message:
Expand All @@ -126,71 +127,69 @@ export default async function handler(req, res) {
return res.status(401).json({ message: "Malicious link entered!" });
}

// Redirection check
try {
// Step 1: Check for HTTP redirects using fetch
const { response, redirectCount } = await fetchWithRedirects(
link,
MAX_REDIRECTS,
);

if (redirectCount >= MAX_REDIRECTS) {
return res.status(400).json({
message: `Suspcious URL detected. If this is a valid URL, please report this issue.`,
if (URI[1]) {
// Redirection check
try {
// Step 1: Check for HTTP redirects using fetch
const { response, redirectCount } = await fetchWithRedirects(
link,
MAX_REDIRECTS,
);

if (redirectCount >= MAX_REDIRECTS) {
return res.status(400).json({
message: `Suspcious URL detected. If this is a valid URL, please report this issue.`,
});
}
} catch (error) {
console.error("Error checking link:", error);
return res.status(500).json({
message: "Error checking the link.",
});
}
} catch (error) {
console.error("Error checking link:", error);
return res.status(500).json({
message: "Error checking the link.",
});
}

if (
process.env.SKIP_SAFE_BROWSING === "true" ||
link.startsWith("magnet:") ||
link.startsWith("ftp:")
) {
console.log("Skipping safe browsing check");
} else {
try {
const response = await fetch(
"https://safebrowsing.googleapis.com/v4/threatMatches:find?key=" +
apiKey,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
client: {
clientId: "maglit-website",
clientVersion: "1.0.0",
},
threatInfo: {
threatTypes: [
"MALWARE",
"SOCIAL_ENGINEERING",
"UNWANTED_SOFTWARE",
"POTENTIALLY_HARMFUL_APPLICATION",
],
platformTypes: ["ANY_PLATFORM"],
threatEntryTypes: ["URL"],
threatEntries: [{ url: `${link}` }],
if (process.env.SKIP_SAFE_BROWSING === "true") {
console.log("Skipping safe browsing check");
} else {
try {
const response = await fetch(
"https://safebrowsing.googleapis.com/v4/threatMatches:find?key=" +
apiKey,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
}),
},
);
body: JSON.stringify({
client: {
clientId: "maglit-website",
clientVersion: "1.0.0",
},
threatInfo: {
threatTypes: [
"MALWARE",
"SOCIAL_ENGINEERING",
"UNWANTED_SOFTWARE",
"POTENTIALLY_HARMFUL_APPLICATION",
],
platformTypes: ["ANY_PLATFORM"],
threatEntryTypes: ["URL"],
threatEntries: [{ url: `${link}` }],
},
}),
},
);

const data = await response.json();
console.log("🚀 => data:", data);
const data = await response.json();
console.log("🚀 => data:", data);

if (data && data?.matches?.length > 0) {
// Handle error cases where the URL might not be checked by Safe Browsing
res.status(401).json({ message: "Malicious link entered!" });
if (data && data?.matches?.length > 0) {
// Handle error cases where the URL might not be checked by Safe Browsing
res.status(401).json({ message: "Malicious link entered!" });
}
} catch (error) {
res.status(500).json({ error: "Failed to check the URL." });
}
} catch (error) {
res.status(500).json({ error: "Failed to check the URL." });
}
}

Expand Down