@hydren/linkvertise
Version:
Linkvertise or something..
90 lines (77 loc) • 2.73 kB
JavaScript
const express = require("express");
let configData = { userid: null, links: {} };
function config(userid) {
if (!userid) throw new Error("User ID is required");
configData.userid = userid;
}
// Generates a random string
function makeid(length) {
let result = '';
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
// Generates a dynamic "Linkvertise-like" URL
function linkvertise(userid, link) {
const token = makeid(8);
const base_url = `https://link-to.net/${userid}/${Math.floor(Math.random() * 1000)}/${token}`;
const href = base_url + "?r=" + Buffer.from(encodeURI(link)).toString("base64");
// store the token for verification
configData.links[token] = link;
return href;
}
/**
* Create Express routes
*/
function create({ type = "router", instance, path, finalPath, onComplete }) {
if (!configData.userid) throw new Error("Please configure your User ID first using .config()");
if (!path || !finalPath) throw new Error("Both path and finalPath are required");
if (typeof onComplete !== "function") throw new Error("onComplete must be a function");
const handler = (req, res) => {
// Generate dynamic link
const targetUrl = `${req.protocol}://${req.headers.host}${finalPath}`;
const lvUrl = linkvertise(configData.userid, targetUrl);
res.redirect(lvUrl);
};
const completionHandler = (req, res) => {
const referer = req.headers.referer || "";
// Check if the user came from your link-to.net link
if (!referer.includes("link-to.net")) {
return res.status(403).send("Invalid access");
}
// Decode the target URL from query
const r = req.query.r;
let target = "";
if (r) {
try {
target = decodeURI(Buffer.from(r, "base64").toString("utf-8"));
} catch {}
}
try {
onComplete(req, target);
} catch (err) {
console.error("Error in onComplete function:", err);
}
res.redirect(target || "/");
};
if (type === "router") {
const router = express.Router();
router.get(path, handler);
router.get(finalPath, completionHandler);
return router;
} else if (type === "app") {
if (!instance) throw new Error("Express instance is required when type is 'app'");
instance.get(path, handler);
instance.get(finalPath, completionHandler);
return instance;
} else {
throw new Error("Invalid type. Must be 'router' or 'app'.");
}
}
module.exports = {
config,
create,
linkvertise,
};