Compare commits

...

14 Commits

Author SHA1 Message Date
2cfecab96f 6.0.0 2024-06-02 15:34:20 +02:00
7eb8a46c7c BREAKING CHANGE(server/client): move from client only to server + client exports 2024-06-02 15:34:19 +02:00
c56e732d6d update description 2024-05-29 14:12:42 +02:00
aff5f2e7d9 update tsconfig 2024-04-14 17:30:20 +02:00
6c38ff36d7 update npmextra.json: githost 2024-04-01 21:34:39 +02:00
b45cda5084 update npmextra.json: githost 2024-04-01 19:58:04 +02:00
dedd3a3f82 update npmextra.json: githost 2024-03-30 21:47:01 +01:00
f2dffb6e88 switch to new org scheme 2023-07-10 02:48:43 +02:00
2a1fbeb183 5.0.4 2023-04-08 11:30:49 +02:00
a6a47d2e96 fix(core): update 2023-04-08 11:30:48 +02:00
84ad6bbcd6 5.0.3 2023-03-23 01:41:35 +01:00
4102c3a692 fix(core): update 2023-03-23 01:41:35 +01:00
6281ab0c80 5.0.2 2022-07-27 11:42:02 +02:00
622c65291e fix(core): update 2022-07-27 11:42:01 +02:00
18 changed files with 7084 additions and 15175 deletions

View File

@ -1,128 +0,0 @@
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: '$CI_BUILD_STAGE'
stages:
- security
- test
- release
- metadata
before_script:
- npm install -g @shipzone/npmci
# ====================
# security stage
# ====================
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --production --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=prod --production
tags:
- docker
allow_failure: true
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=dev
tags:
- docker
allow_failure: true
# ====================
# test stage
# ====================
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- lossless
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
allow_failure: true
only:
- tags
script:
- npmci command npm install -g typescript
- npmci npm prepare
- npmci npm install
tags:
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
stage: metadata
script:
- npmci node install stable
- npmci npm prepare
- npmci npm install
- npmci command npm run buildDocs
tags:
- lossless
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

View File

@ -2,17 +2,30 @@
"gitzone": { "gitzone": {
"projectType": "npm", "projectType": "npm",
"module": { "module": {
"githost": "gitlab.com", "githost": "code.foss.global",
"gitscope": "pushrocks", "gitscope": "push.rocks",
"gitrepo": "smartdns", "gitrepo": "smartdns",
"description": "smart dns methods written in TypeScript", "description": "A TypeScript library for smart DNS methods, supporting various DNS records and providers.",
"npmPackagename": "@pushrocks/smartdns", "npmPackagename": "@push.rocks/smartdns",
"license": "MIT" "license": "MIT",
"keywords": [
"DNS",
"TypeScript",
"Node.js",
"Google DNS",
"Cloudflare",
"DNS records",
"DNS resolution",
"DNSSEC"
]
} }
}, },
"npmci": { "npmci": {
"npmGlobalTools": [], "npmGlobalTools": [],
"npmAccessLevel": "public", "npmAccessLevel": "public",
"npmRegistryUrl": "registry.npmjs.org" "npmRegistryUrl": "registry.npmjs.org"
},
"tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
} }
} }

14936
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,45 +1,53 @@
{ {
"name": "@pushrocks/smartdns", "name": "@push.rocks/smartdns",
"version": "5.0.1", "version": "6.0.0",
"private": false, "private": false,
"description": "smart dns methods written in TypeScript", "description": "A TypeScript library for smart DNS methods, supporting various DNS records and providers.",
"main": "dist_ts/index.js", "exports": {
"typings": "dist_ts/index.d.ts", ".": "./dist_ts_server/index.js",
"./server": "./dist_ts_server/index.js",
"./client": "./dist_ts_client/index.js"
},
"scripts": { "scripts": {
"test": "(tstest test/)", "test": "(tstest test/)",
"build": "(tsbuild --web --allowimplicitany)", "build": "(tsbuild tsfolders --web --allowimplicitany)",
"buildDocs": "tsdoc" "buildDocs": "tsdoc"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+ssh://git@gitlab.com/pushrocks/dnsly.git" "url": "https://code.foss.global/push.rocks/smartdns.git"
}, },
"keywords": [ "keywords": [
"dns", "DNS",
"google dns", "TypeScript",
"dns record" "Node.js",
"Google DNS",
"Cloudflare",
"DNS records",
"DNS resolution",
"DNSSEC"
], ],
"author": "Lossless GmbH", "author": "Lossless GmbH",
"license": "MIT", "license": "MIT",
"bugs": { "bugs": {
"url": "https://gitlab.com/pushrocks/dnsly/issues" "url": "https://gitlab.com/pushrocks/dnsly/issues"
}, },
"homepage": "https://gitlab.com/pushrocks/dnsly#README", "homepage": "https://code.foss.global/push.rocks/smartdns",
"dependencies": { "dependencies": {
"@pushrocks/smartdelay": "^2.0.13", "@push.rocks/smartdelay": "^3.0.1",
"@pushrocks/smartenv": "^5.0.2", "@push.rocks/smartenv": "^5.0.5",
"@pushrocks/smartpromise": "^3.1.7", "@push.rocks/smartpromise": "^4.0.2",
"@pushrocks/smartrequest": "^1.1.56", "@push.rocks/smartrequest": "^2.0.15",
"@tsclass/tsclass": "^4.0.17", "@tsclass/tsclass": "^4.0.54",
"dns2": "^2.0.5" "@types/dns-packet": "^5.6.5",
"dns-packet": "^5.6.1"
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.63", "@git.zone/tsbuild": "^2.1.66",
"@gitzone/tstest": "^1.0.72", "@git.zone/tsrun": "^1.2.44",
"@pushrocks/tapbundle": "^5.0.4", "@git.zone/tstest": "^1.0.77",
"@types/node": "^18.6.1", "@push.rocks/tapbundle": "^5.0.8",
"tslint": "^6.1.3", "@types/node": "^20.13.0"
"tslint-config-prettier": "^1.18.0"
}, },
"files": [ "files": [
"ts/**/*", "ts/**/*",

6719
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

1
readme.hints.md Normal file
View File

@ -0,0 +1 @@

147
readme.md
View File

@ -1,53 +1,124 @@
# @pushrocks/smartdns # @push.rocks/smartdns
smart dns methods written in TypeScript smart dns methods written in TypeScript
## Availabililty and Links ## Install
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartdns)
* [gitlab.com (source)](https://gitlab.com/pushrocks/smartdns)
* [github.com (source mirror)](https://github.com/pushrocks/smartdns)
* [docs (typedoc)](https://pushrocks.gitlab.io/smartdns/)
## Status for master To install `@push.rocks/smartdns`, use the following command with npm:
Status Category | Status Badge ```bash
-- | -- npm install @push.rocks/smartdns --save
GitLab Pipelines | [![pipeline status](https://gitlab.com/pushrocks/smartdns/badges/master/pipeline.svg)](https://lossless.cloud) ```
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/pushrocks/smartdns/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@pushrocks/smartdns)](https://lossless.cloud) Or with `yarn`:
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/pushrocks/smartdns)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud) ```bash
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/) yarn add @push.rocks/smartdns
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud) ```
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@pushrocks/smartdns)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@pushrocks/smartdns)](https://lossless.cloud) Make sure you have a TypeScript environment setup to utilize the library effectively.
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@pushrocks/smartdns)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
## Usage ## Usage
Use TypeScript for best in class instellisense. `@push.rocks/smartdns` is a comprehensive library aimed at facilitating smart DNS operations, leveraging TypeScript for enhanced development experience. This section aims to cover several real-world scenarios demonstrating the library's capabilities, from basic DNS lookups to more advanced DNS management tasks.
### Getting Started
First, ensure you import the module into your TypeScript project:
```typescript ```typescript
const mySmartDns = new smartdns.SmartDns(); // uses Google DNS Https API import { Smartdns } from '@push.rocks/smartdns';
const demoRecord = await mySmartDns.getRecord('example.com', 'AAAA'); // returns promise
/*
demoRecord looks like this:
{
name: 'example.com',
type: 'A',
dnsSecEnabled: true,
value: '104.24.103.243'
}
*/
``` ```
## Contribution ### Basic DNS Record Lookup
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :) Often, the need arises to fetch various DNS records for a domain. `@push.rocks/smartdns` simplifies this by providing intuitive methods.
For further information read the linked docs at the top of this readme. #### Fetching A Records
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh) To fetch an "A" record for a domain:
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com) ```typescript
const dnsManager = new Smartdns({});
const aRecords = await dnsManager.getRecordsA('example.com');
console.log(aRecords);
```
#### Fetching AAAA Records
Similarly, for "AAAA" records:
```typescript
const aaaaRecords = await dnsManager.getRecordsAAAA('example.com');
console.log(aaaaRecords);
```
### Advanced DNS Management
Beyond simple queries, `@push.rocks/smartdns` offers functionalities suitable for more complex DNS management scenarios.
#### Checking DNS Propagation
When changing DNS records, ensuring that the new records have propagated fully is crucial. `@push.rocks/smartdns` facilitates this with a method to check a DNS record until it is available globally.
```typescript
const recordType = 'TXT'; // Record type: A, AAAA, CNAME, TXT etc.
const expectedValue = 'your_expected_value';
const isAvailable = await dnsManager.checkUntilAvailable('example.com', recordType, expectedValue);
if (isAvailable) {
console.log('Record propagated successfully.');
} else {
console.log('Record propagation failed or timed out.');
}
```
### Leveraging DNS for Application Logic
DNS records can serve beyond mere domain-to-IP resolution; they can be instrumental in application logic, such as feature flagging or environment-specific configurations.
#### Example: Feature Flagging via TXT Records
Consider leveraging TXT records for enabling/disabling features dynamically without deploying new code.
```typescript
const txtRecords = await dnsManager.getRecordsTxt('features.example.com');
const featureFlags = txtRecords.reduce((acc, record) => {
const [flag, isEnabled] = record.value.split('=');
acc[flag] = isEnabled === 'true';
return acc;
}, {});
if (featureFlags['NewFeature']) {
// Logic to enable the new feature
}
```
### Conclusion
`@push.rocks/smartdns` offers a versatile set of tools for DNS querying and management, tailored for applications at any scale. The examples provided illustrate the library's potential use cases, highlighting its applicability in various scenarios from basic lookups to facilitating complex application features through DNS.
For the full spectrum of functionalities, including detailed method documentation and additional use cases, consult the module's [TypeDoc documentation](https://pushrocks.gitlab.io/smartdns/). This will serve as a comprehensive guide to leveraging `@push.rocks/smartdns` effectively in your projects.
Remember, DNS changes might take time to propagate worldwide, and the utility methods provided by `@push.rocks/smartdns` for checking record availability will be invaluable in managing these changes seamlessly.
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

View File

@ -1,6 +1,6 @@
import { expect, tap } from '@pushrocks/tapbundle'; import { expect, tap } from '@push.rocks/tapbundle';
import * as smartdns from '../ts/index.js'; import * as smartdns from '../ts_client/index.js';
let testDnsly: smartdns.Smartdns; let testDnsly: smartdns.Smartdns;
@ -10,7 +10,7 @@ tap.test('should create an instance of Dnsly', async () => {
}); });
tap.test('should get an A DNS Record', async () => { tap.test('should get an A DNS Record', async () => {
return expect(await testDnsly.getRecordA('dnsly_a.bleu.de')).toEqual([ return expect(await testDnsly.getRecordsA('dnsly_a.bleu.de')).toEqual([
{ {
name: 'dnsly_a.bleu.de', name: 'dnsly_a.bleu.de',
value: '127.0.0.1', value: '127.0.0.1',
@ -21,7 +21,7 @@ tap.test('should get an A DNS Record', async () => {
}); });
tap.test('should get an AAAA Record', async () => { tap.test('should get an AAAA Record', async () => {
return expect(await testDnsly.getRecordAAAA('dnsly_aaaa.bleu.de')).toEqual([ return expect(await testDnsly.getRecordsAAAA('dnsly_aaaa.bleu.de')).toEqual([
{ {
name: 'dnsly_aaaa.bleu.de', name: 'dnsly_aaaa.bleu.de',
value: '::1', value: '::1',
@ -32,7 +32,7 @@ tap.test('should get an AAAA Record', async () => {
}); });
tap.test('should get a txt record', async () => { tap.test('should get a txt record', async () => {
return expect(await testDnsly.getRecordTxt('dnsly_txt.bleu.de')).toEqual([ return expect(await testDnsly.getRecordsTxt('dnsly_txt.bleu.de')).toEqual([
{ {
name: 'dnsly_txt.bleu.de', name: 'dnsly_txt.bleu.de',
value: 'sometext_txt', value: 'sometext_txt',
@ -43,29 +43,35 @@ tap.test('should get a txt record', async () => {
}); });
tap.test('should, get a mx record for a domain', async () => { tap.test('should, get a mx record for a domain', async () => {
const res = await testDnsly.getRecord('bleu.de', 'MX'); const res = await testDnsly.getRecords('bleu.de', 'MX');
console.log(res); console.log(res);
}); });
tap.test('should check until DNS is available', async () => { tap.test('should check until DNS is available', async () => {
return expect(await testDnsly.checkUntilAvailable('dnsly_txt.bleu.de', 'TXT', 'sometext_txt')).toBeTrue(); return expect(
await testDnsly.checkUntilAvailable('dnsly_txt.bleu.de', 'TXT', 'sometext_txt')
).toBeTrue();
}); });
tap.test('should check until DNS is available an return false if it fails', async () => { tap.test('should check until DNS is available an return false if it fails', async () => {
return expect(await testDnsly.checkUntilAvailable('dnsly_txt.bleu.de', 'TXT', 'sometext_txt2')).toBeFalse() return expect(
await testDnsly.checkUntilAvailable('dnsly_txt.bleu.de', 'TXT', 'sometext_txt2')
).toBeFalse();
}); });
tap.test('should check until DNS is available an return false if it fails', async () => { tap.test('should check until DNS is available an return false if it fails', async () => {
return expect(await testDnsly.checkUntilAvailable('dnsly_txtNotThere.bleu.de', 'TXT', 'sometext_txt2')).toBeFalse() return expect(
await testDnsly.checkUntilAvailable('dnsly_txtNotThere.bleu.de', 'TXT', 'sometext_txt2')
).toBeFalse();
}); });
tap.test('should get name server for hostname', async () => { tap.test('should get name server for hostname', async () => {
let result = await testDnsly.getNameServer('bleu.de'); let result = await testDnsly.getNameServers('bleu.de');
console.log(result); console.log(result);
}); });
tap.test('should detect dns sec', async () => { tap.test('should detect dns sec', async () => {
const result = await testDnsly.getRecordA('lossless.com'); const result = await testDnsly.getRecordsA('lossless.com');
console.log(result[0]); console.log(result[0]);
expect(result[0].dnsSecEnabled).toBeTrue(); expect(result[0].dnsSecEnabled).toBeTrue();
}); });

0
test/test.server.ts Normal file
View File

View File

@ -1,8 +0,0 @@
/**
* autocreated commitinfo by @pushrocks/commitinfo
*/
export const commitinfo = {
name: '@pushrocks/smartdns',
version: '5.0.1',
description: 'smart dns methods written in TypeScript'
}

View File

@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartdns',
version: '5.0.4',
description: 'smart dns methods written in TypeScript'
}

View File

@ -2,7 +2,7 @@ import * as plugins from './dnsly.plugins.js';
export type TDnsProvider = 'google' | 'cloudflare'; export type TDnsProvider = 'google' | 'cloudflare';
export const makeNodeProcessUseDnsProvider = async (providerArg: TDnsProvider) => { export const makeNodeProcessUseDnsProvider = (providerArg: TDnsProvider) => {
switch (providerArg) { switch (providerArg) {
case 'cloudflare': case 'cloudflare':
plugins.dns.setServers([ plugins.dns.setServers([
@ -78,7 +78,7 @@ export class Smartdns {
try { try {
let myRecordArray: plugins.tsclass.network.IDnsRecord[]; let myRecordArray: plugins.tsclass.network.IDnsRecord[];
if (runCycles % 2 === 0 || !plugins.dns) { if (runCycles % 2 === 0 || !plugins.dns) {
myRecordArray = await this.getRecord(recordNameArg, recordTypeArg); myRecordArray = await this.getRecords(recordNameArg, recordTypeArg, 0);
} else { } else {
myRecordArray = await this.getRecordWithNodeDNS(recordNameArg, recordTypeArg); myRecordArray = await this.getRecordWithNodeDNS(recordNameArg, recordTypeArg);
} }
@ -110,37 +110,50 @@ export class Smartdns {
/** /**
* get A Dns Record * get A Dns Record
*/ */
public async getRecordA(recordNameArg: string): Promise<plugins.tsclass.network.IDnsRecord[]> { public async getRecordsA(recordNameArg: string): Promise<plugins.tsclass.network.IDnsRecord[]> {
return await this.getRecord(recordNameArg, 'A'); return await this.getRecords(recordNameArg, 'A');
} }
/** /**
* get AAAA Record * get AAAA Record
*/ */
public async getRecordAAAA(recordNameArg: string) { public async getRecordsAAAA(recordNameArg: string) {
return await this.getRecord(recordNameArg, 'AAAA'); return await this.getRecords(recordNameArg, 'AAAA');
} }
/** /**
* gets a txt record * gets a txt record
*/ */
public async getRecordTxt(recordNameArg: string): Promise<plugins.tsclass.network.IDnsRecord[]> { public async getRecordsTxt(recordNameArg: string): Promise<plugins.tsclass.network.IDnsRecord[]> {
return await this.getRecord(recordNameArg, 'TXT'); return await this.getRecords(recordNameArg, 'TXT');
} }
public async getRecord( public async getRecords(
recordNameArg: string, recordNameArg: string,
recordTypeArg: plugins.tsclass.network.TDnsRecordType recordTypeArg: plugins.tsclass.network.TDnsRecordType,
retriesCounterArg = 20
): Promise<plugins.tsclass.network.IDnsRecord[]> { ): Promise<plugins.tsclass.network.IDnsRecord[]> {
const requestUrl = `https://cloudflare-dns.com/dns-query?name=${recordNameArg}&type=${recordTypeArg}&do=1`; const requestUrl = `https://cloudflare-dns.com/dns-query?name=${recordNameArg}&type=${recordTypeArg}&do=1`;
const response = await plugins.smartrequest.request(requestUrl, {
method: 'GET',
headers: {
accept: 'application/dns-json',
},
});
const returnArray: plugins.tsclass.network.IDnsRecord[] = []; const returnArray: plugins.tsclass.network.IDnsRecord[] = [];
const responseBody: IGoogleDNSHTTPSResponse = response.body; const getResponseBody = async (counterArg = 0): Promise<IGoogleDNSHTTPSResponse> => {
const response = await plugins.smartrequest.request(requestUrl, {
method: 'GET',
headers: {
accept: 'application/dns-json',
},
});
const responseBody: IGoogleDNSHTTPSResponse = response.body;
if (responseBody?.Status !== 0 && counterArg < retriesCounterArg) {
await plugins.smartdelay.delayFor(500);
return getResponseBody(counterArg++);
} else {
return responseBody;
}
};
const responseBody = await getResponseBody();
if (!responseBody.Answer || !typeof responseBody.Answer[Symbol.iterator]) {
return returnArray;
}
for (const dnsEntry of responseBody.Answer) { for (const dnsEntry of responseBody.Answer) {
if (dnsEntry.data.startsWith('"') && dnsEntry.data.endsWith('"')) { if (dnsEntry.data.startsWith('"') && dnsEntry.data.endsWith('"')) {
dnsEntry.data = dnsEntry.data.replace(/^"(.*)"$/, '$1'); dnsEntry.data = dnsEntry.data.replace(/^"(.*)"$/, '$1');
@ -186,7 +199,7 @@ export class Smartdns {
return done.promise; return done.promise;
} }
public async getNameServer(domainNameArg: string): Promise<string[]> { public async getNameServers(domainNameArg: string): Promise<string[]> {
const done = plugins.smartpromise.defer<string[]>(); const done = plugins.smartpromise.defer<string[]>();
plugins.dns.resolveNs(domainNameArg, (err, result) => { plugins.dns.resolveNs(domainNameArg, (err, result) => {
if (!err) { if (!err) {

View File

@ -1,4 +1,4 @@
import * as smartenv from '@pushrocks/smartenv'; import * as smartenv from '@push.rocks/smartenv';
const smartenvInstance = new smartenv.Smartenv(); const smartenvInstance = new smartenv.Smartenv();
// node native scope // node native scope
import type dnsType from 'dns'; import type dnsType from 'dns';
@ -7,9 +7,9 @@ const dns: typeof dnsType = await smartenvInstance.getSafeNodeModule('dns');
export { dns }; export { dns };
// pushrocks scope // pushrocks scope
import * as smartdelay from '@pushrocks/smartdelay'; import * as smartdelay from '@push.rocks/smartdelay';
import * as smartpromise from '@pushrocks/smartpromise'; import * as smartpromise from '@push.rocks/smartpromise';
import * as smartrequest from '@pushrocks/smartrequest'; import * as smartrequest from '@push.rocks/smartrequest';
export { smartdelay, smartenv, smartpromise, smartrequest }; export { smartdelay, smartenv, smartpromise, smartrequest };

1
ts_client/index.ts Normal file
View File

@ -0,0 +1 @@
export * from './classes.dnsclient.js';

View File

@ -0,0 +1,120 @@
import * as plugins from './plugins.js';
interface IDnsServerOptions {
httpsKey: string;
httpsCert: string;
httpsPort: number;
udpPort: number;
}
class DnsServer {
private udpServer: plugins.dgram.Socket;
private httpsServer: plugins.https.Server;
constructor(private options: IDnsServerOptions) {
this.udpServer = plugins.dgram.createSocket('udp4');
this.setupUdpServer();
this.httpsServer = plugins.https.createServer(
{
key: plugins.fs.readFileSync(options.httpsKey),
cert: plugins.fs.readFileSync(options.httpsCert)
},
this.handleHttpsRequest.bind(this)
);
}
private setupUdpServer(): void {
this.udpServer.on('message', (msg, rinfo) => {
const request = plugins.dnsPacket.decode(msg);
const response = {
type: 'response' as const,
id: request.id,
flags: plugins.dnsPacket.RECURSION_DESIRED | plugins.dnsPacket.RECURSION_AVAILABLE,
questions: request.questions,
answers: [] as plugins.dnsPacket.Answer[]
};
const question = request.questions[0];
console.log(`UDP query for ${question.name} of type ${question.type}`);
if (question.type === 'A') {
response.answers.push({
name: question.name,
type: 'A',
class: 'IN',
ttl: 300,
data: '127.0.0.1'
});
}
const responseData = plugins.dnsPacket.encode(response);
this.udpServer.send(responseData, rinfo.port, rinfo.address);
});
this.udpServer.on('error', (err) => {
console.error(`UDP Server error:\n${err.stack}`);
this.udpServer.close();
});
this.udpServer.bind(this.options.udpPort, '0.0.0.0', () => {
console.log(`UDP DNS server running on port ${this.options.udpPort}`);
});
}
private handleHttpsRequest(req: plugins.http.IncomingMessage, res: plugins.http.ServerResponse): void {
if (req.method === 'POST' && req.url === '/dns-query') {
let body: Buffer[] = [];
req.on('data', chunk => {
body.push(chunk);
}).on('end', () => {
const msg = Buffer.concat(body);
const request = plugins.dnsPacket.decode(msg);
const response = {
type: 'response' as const,
id: request.id,
flags: plugins.dnsPacket.RECURSION_DESIRED | plugins.dnsPacket.RECURSION_AVAILABLE,
questions: request.questions,
answers: [] as plugins.dnsPacket.Answer[]
};
const question = request.questions[0];
console.log(`DoH query for ${question.name} of type ${question.type}`);
if (question.type === 'A') {
response.answers.push({
name: question.name,
type: 'A',
class: 'IN',
ttl: 300,
data: '127.0.0.1'
});
}
const responseData = plugins.dnsPacket.encode(response);
res.writeHead(200, { 'Content-Type': 'application/dns-message' });
res.end(responseData);
});
} else {
res.writeHead(404);
res.end();
}
}
public start(): void {
this.httpsServer.listen(this.options.httpsPort, () => {
console.log(`DoH server running on port ${this.options.httpsPort}`);
});
}
public stop(): void {
this.udpServer.close(() => {
console.log('UDP DNS server stopped');
});
this.httpsServer.close(() => {
console.log('HTTPS DNS server stopped');
});
}
}

0
ts_server/index.ts Normal file
View File

17
ts_server/plugins.ts Normal file
View File

@ -0,0 +1,17 @@
import fs from 'fs';
import http from 'http';
import https from 'https';
import dgram from 'dgram';
export {
fs,
http,
https,
dgram,
}
import * as dnsPacket from 'dns-packet';
export {
dnsPacket
}

View File

@ -3,8 +3,12 @@
"experimentalDecorators": true, "experimentalDecorators": true,
"useDefineForClassFields": false, "useDefineForClassFields": false,
"target": "ES2022", "target": "ES2022",
"module": "ES2022", "module": "NodeNext",
"moduleResolution": "nodenext", "moduleResolution": "NodeNext",
"esModuleInterop": true "esModuleInterop": true,
} "verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
} }