DNS stuff

This commit is contained in:
2024-08-10 17:47:44 -04:00
parent 92df05540b
commit 3df3341235
12 changed files with 587 additions and 11 deletions
+154
View File
@@ -0,0 +1,154 @@
'use strict';
const crypto = require("crypto");
const conf = require('../conf');
const Table = require('../utils/redis_model');
const ModelPs = require('../utils/model_pubsub');
const tldExtract = require('tld-extract').parse_host;
const providers = {
PorkBun: require('./dns_provider/porkbun'),
DigitalOcean: require('./dns_provider/digitalocean'),
};
class Domain extends Table{
static _key = 'domain';
static _keyMap = {
'created_by': {isRequired: true, type: 'string', min: 3, max: 500},
'created_on': {default: function(){return (new Date).getTime()}},
'updated_by': {default:"__NONE__", isRequired: false, type: 'string',},
'updated_on': {default: function(){return (new Date).getTime()}, always: true},
'domain': {isRequired: true, type: 'string'},
'dnsProvider_id': {isRequired: true, type: 'string'},
}
static async get(data, ...args){
let instance = await super.get(data, ...args);
// instance.provider = (await DnsProvider.get(instance.dnsProvider_id)).provider;
return instance;
}
static async getByProviderId(id){
let domains = await this.listDetail();
let results = [];
for(let domain of domains){
if(domain.dnsProvider_id == id) results.push(domain);
}
return results;
}
}
class DnsProvider extends Table{
static _key = 'id';
static _keyMap = {
'created_by': {isRequired: true, type: 'string', min: 3, max: 500},
'created_on': {default: function(){return (new Date).getTime()}},
'updated_by': {default:"__NONE__", isRequired: false, type: 'string',},
'updated_on': {default: function(){return (new Date).getTime()}, always: true},
'id': {default: ()=>crypto.randomBytes(8).toString("hex")},
'name': {isRequired: true, type: 'string'},
'dnsProvider': {isRequired: true, type: 'string'},
}
static __intraModel(provider){
if(!Object.keys(providers).includes(provider)) throw new Error('Invalid DNS provider')
let Provider = providers[provider];
let _keyMap = {...this._keyMap, ...Provider._keyMap};
return ({
[this.name] : class extends this {
static _keyMap = _keyMap;
static Provider = Provider;
}
})[this.name];
}
static listProviders(){
let out = [];
for(let provider in providers){
out.push({
name: provider,
displayName: providers[provider].displayName || provider,
displayIconUni: providers[provider].displayIconUni || '?',
displayIconHtml: providers[provider].displayIconHtml || '<i class="fa-solid fa-question"></i>',
fields: providers[provider]._keyMap,
});
}
return out;
}
static async create(data, ...args){
let __intraModel = this.__intraModel(data.dnsProvider)
let instance = await super.create.call(__intraModel, data);
if(!data.noUpdate) instance.updateDomains();
return instance;
}
static async get(data, ...args){
let instance = await super.get(data);
let __intraModel = this.__intraModel(instance.dnsProvider)
instance = await super.get.call(__intraModel, data);
instance.provider = new __intraModel.Provider(instance);
// instance.domains = Domain.getByProviderId(this.id);
return instance;
}
async updateDomains(){
try{
let domains = await this.provider.listDomains();
console.log('got domains', domains)
for(let domain of domains){
if(!(await Domain.exists(domain.domain))){
await Domain.create({
created_by: this.created_by,
domain: domain.domain,
dnsProvider_id: this.id
});
}
}
}catch(error){
console.error('updateDomains error', error)
}
}
async getDomains(){
return Domains.getByProviderId(this.id)
}
async remove(){
let id = this.id
let instance = await super.remove()
// get all domains for this provider and delete them
return instance
}
toJSON(){
return {
...super.toJSON(),
domains: this.domains,
}
}
}
Domain = ModelPs(Domain);
DnsProvider = ModelPs(DnsProvider);
module.exports = {Domain, DnsProvider}
if(require.main === module){(async function(){try{
const conf = require('../conf');
// console.log(aw)
}catch(error){
console.log('IIFE Error:', error)
}})()}
+125
View File
@@ -0,0 +1,125 @@
'use strict';
const axios = require('axios');
class PorkBun{
static _keyMap = {
'apiKey': {isRequired: true, type: 'string', isPrivate: true, displayName: 'API key'},
'secretApiKey': {isRequired: true, type: 'string', isPrivate: true, displayName: 'API Secret key'},
}
baseUrl = 'https://api.porkbun.com/api/json/v3';
constructor(args){
this.apiKey = args.apiKey;
this.secretApiKey = args.secretApiKey;
}
async post(url, data){
let res;
try{
data = {
...(data || {}),
secretapikey: this.secretApiKey,
apikey: this.apiKey,
};
res = await axios.post(`${this.baseUrl}${url}`, data);
return res;
}catch(error){
throw new Error(`PorkPun API ${error.response.status}: ${error.response.data.message}`)
}
}
__typeCheck(type){
if(!['A', 'MX', 'CNAME', 'ALIAS', 'TXT', 'NS', 'AAAA', 'SRV', 'TLSA', 'CAA', 'HTTPS', 'SVCB'].includes(type)) throw new Error('PorkBun API: Invalid type passed')
}
__parseName(domain, name){
if(name && !name.endsWith('.'+domain)){
return `${name}.${domain}`
}
return name;
}
async getRecords(domain, options){
let res = await this.post(`/dns/retrieve/${domain}`);
if(!options) return res.data.records;
if(options.data) options.content = options.data;
if(options.type) this.__typeCheck(options.type);
if(options.name) options.name = this.__parseName(domain, options.name);
let records = [];
for(let record of res.data.records){
let matchCount = 0
for(let option in options){
if(record[option] === options[option] && ++matchCount === Object.keys(options).length){
records.push(record)
break;
}
}
}
return records;
}
async deleteRecordById(domain, id){
let res = await this.post(`/dns/delete/${domain}/${id}`);
return res.data;
}
async deleteRecords(domain, options){
let records = await this.getRecords(domain, options);
// console.log('PorkBun.deleteRecords', records)
for(let record of records){
await this.deleteRecordById(domain, record.id)
}
}
async createRecord(domain, options){
this.__typeCheck(options.type);
if(!options.content) throw new Error('PorkBun API: `content` key is required for this action')
// if(options.name) options.name = this.__parseName(domain, options.name);
// console.log('PorkBun.createRecord to send:', domain, options)
let res = await this.post(`/dns/create/${domain}`, options);
return res.data;
}
async createRecordForce(domain, options){
let {content, ...removed} = options;
// console.log('new options', removed)
let records = await this.getRecords(domain, removed);
// console.log('createRecordForce', records)
if(records.length){
// console.log('calling delete on', records[0].id)
// process.exit(0)
await this.deleteRecordById(domain, records[0].id)
}
return await this.createRecord(domain, options)
}
async listDomains(){
let res = await this.post(`/domain/listAll`, {"includeLabels": "yes"});
return res.data.domains;
}
}
module.exports = PorkBun;
if(require.main === module){(async function(){try{
const conf = require('../conf');
// let porkBun = new PorkBun(conf.porkBun.apiKey, conf.porkBun.secretApiKey);
// console.log(await porkBun.listDomains())
// console.log(await porkBun.deleteRecordById('holycore.quest', '415509355'))
// console.log('IIFE', await porkBun.createRecordForce('holycore.quest', {type:'A', name: 'testapi', content: '127.0.0.5'}))
// console.log('IIFE', await porkBun.getRecords('holycore.quest', {type:'A', name: 'testapi'}))
}catch(error){
console.log('IIFE Error:', error)
}})()}
+3 -3
View File
@@ -4,7 +4,7 @@ const Table = require('../utils/redis_model');
const ModelPs = require('../utils/model_pubsub');
const tldExtract = require('tld-extract').parse_host;
const PorkBun = require('../utils/porkbun');
const PorkBun = require('./dns_provider/porkbun');
const LetsEncrypt = require('../utils/letsencrypt');
const conf = require('../conf');
@@ -353,8 +353,8 @@ try{
// console.log('IIFE res:\n', res)
// console.log(Host.test(55))
console.log(await Host.list())
console.log(await Cached.listDetail())
// console.log(await Host.list())
// console.log(await Cached.listDetail())
// console.log('IIFE lookup:', Host.lookUp('bld3324sdf.test.holycore.quest'))
+1 -1
View File
@@ -12,7 +12,7 @@ class User extends Table{
'updated_by': {default:"__NONE__", isRequired: false, type: 'string',},
'updated_on': {default: function(){return (new Date).getTime()}, always: true},
'username': {isRequired: true, type: 'string', min: 3, max: 500},
'password': {isRequired: true, type: 'string', min: 3, max: 500},
'password': {isRequired: true, type: 'string', min: 3, max: 500, isPrivate: true},
'backing': {default:"redis", isRequired: false, type: 'string',},
}