This repository has been archived on 2022-10-07. You can view files and clone it, but cannot push or open issues or pull requests.
skynet-webportal/packages/dnslink-api/src/index.js

72 lines
2.2 KiB
JavaScript
Raw Normal View History

2021-06-25 12:05:36 +00:00
const dns = require("dns");
const express = require("express");
const isValidDomain = require("is-valid-domain");
const host = process.env.DNSLINK_API_HOSTNAME || "0.0.0.0";
const port = Number(process.env.DNSLINK_API_PORT) || 3100;
2021-06-25 12:05:36 +00:00
const server = express();
const dnslinkNamespace = "skynet-ns";
const dnslinkRegExp = new RegExp(`^dnslink=/${dnslinkNamespace}/.+$`);
const dnslinkSkylinkRegExp = new RegExp(`^dnslink=/${dnslinkNamespace}/([a-zA-Z0-9_-]{46}|[a-z0-9]{55})`);
const hint = `valid example: dnslink=/${dnslinkNamespace}/3ACpC9Umme41zlWUgMQh1fw0sNwgWwyfDDhRQ9Sppz9hjQ`;
2021-06-25 12:05:36 +00:00
server.get("/dnslink/:name", async (req, res) => {
2021-08-27 12:15:22 +00:00
const success = (skylink) => res.send(skylink);
const failure = (message) => res.status(400).send(message);
2021-06-25 12:05:36 +00:00
if (!isValidDomain(req.params.name)) {
return failure(`"${req.params.name}" is not a valid domain`);
}
const lookup = `_dnslink.${req.params.name}`;
dns.resolveTxt(lookup, (error, records) => {
if (error) {
if (error.code === "ENOTFOUND") {
return failure(`ENOTFOUND: ${lookup} TXT record doesn't exist`);
}
if (error.code === "ENODATA") {
return failure(`ENODATA: ${lookup} dns lookup returned no data`);
}
return failure(`Failed to fetch ${lookup} TXT record: ${error.message}`);
}
if (records.length === 0) {
return failure(`No TXT record found for ${lookup}`);
}
const dnslinks = records.flat().filter((record) => dnslinkRegExp.test(record));
if (dnslinks.length === 0) {
return failure(`TXT records for ${lookup} found but none of them contained valid skynet dnslink - ${hint}`);
2021-06-25 12:05:36 +00:00
}
if (dnslinks.length > 1) {
return failure(`Multiple TXT records with valid skynet dnslink found for ${lookup}, only one allowed`);
2021-06-25 12:05:36 +00:00
}
const [dnslink] = dnslinks;
const matchSkylink = dnslink.match(dnslinkSkylinkRegExp);
2021-06-25 12:05:36 +00:00
if (!matchSkylink) {
return failure(`TXT record with skynet dnslink for ${lookup} contains invalid skylink - ${hint}`);
2021-06-25 12:05:36 +00:00
}
const skylink = matchSkylink[1];
console.log(`${req.params.name} => ${skylink}`);
return success(skylink);
});
});
server.listen(port, host, (error) => {
if (error) throw error;
console.info(`Server listening at http://${host}:${port}`);
});