Initial commit
This commit is contained in:
commit
af97bccb0e
10 changed files with 548 additions and 0 deletions
60
index.js
Normal file
60
index.js
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
// development endpoint (use ngrok)
|
||||
|
||||
const http = require('http');
|
||||
const argv = require('minimist')(process.argv.slice(2));
|
||||
const port = parseInt(argv.port || 3000);
|
||||
const record_prefix = 'forward-domain=';
|
||||
|
||||
const {
|
||||
default: axios
|
||||
} = require('axios');
|
||||
|
||||
/**
|
||||
* @type {Object<string, {expire: number, expand: boolean, url: string}>}
|
||||
*/
|
||||
const resolveCache = {};
|
||||
|
||||
async function buildCache(host) {
|
||||
const resolve = await axios(`https://dns.google/resolve?name=${encodeURIComponent(host)}&type=TXT`);
|
||||
for (const head of resolve.data.Answer) {
|
||||
let url = head.data.slice(record_prefix.length);
|
||||
let expand = false;
|
||||
if (url.endsWith('*')) {
|
||||
url = url.substr(0, -1);
|
||||
expand = true;
|
||||
}
|
||||
return {
|
||||
url,
|
||||
expand,
|
||||
expire: Date.now() + Math.max(head.TTL, 86400) * 1000,
|
||||
};
|
||||
}
|
||||
throw new Error(record_prefix + ' TXT is missing');
|
||||
}
|
||||
|
||||
const server = http.createServer(async function (req, res) {
|
||||
try {
|
||||
let cache = resolveCache[req.headers.host];
|
||||
if (!cache || (Date.now() > cache.expire)) {
|
||||
cache = await buildCache(req.headers.host);
|
||||
resolveCache[req.headers.host] = cache;
|
||||
}
|
||||
req.statusCode = 301;
|
||||
req.headers.location = cache.expand ? cache.url + req.url : cache.url;
|
||||
return;
|
||||
} catch (error) {
|
||||
res.statusCode = 400;
|
||||
res.write(error.message || 'Unknown error');
|
||||
} finally {
|
||||
res.end();
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
if (require.main === module) {
|
||||
server.listen(port, function () {
|
||||
console.log(`server start at port ${port}`);
|
||||
});
|
||||
} else {
|
||||
module.exports = server
|
||||
}
|
||||
Loading…
Add table
editor.link_modal.header
Reference in a new issue