smartdns/readme.md

385 lines
11 KiB
Markdown
Raw Permalink Normal View History

2024-04-14 15:30:20 +00:00
# @push.rocks/smartdns
A TypeScript library for smart DNS methods, supporting various DNS records and providers.
2024-04-14 15:30:20 +00:00
## Install
To install `@push.rocks/smartdns`, use the following command with npm:
```bash
npm install @push.rocks/smartdns --save
```
Or with `yarn`:
```bash
yarn add @push.rocks/smartdns
```
Make sure you have a TypeScript environment set up to utilize the library effectively.
2017-07-18 13:45:06 +00:00
## Usage
2024-04-14 15:30:20 +00:00
`@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
import { Smartdns } from '@push.rocks/smartdns';
```
### Basic DNS Record Lookup
Often, the need arises to fetch various DNS records for a domain. `@push.rocks/smartdns` simplifies this by providing intuitive methods.
#### Fetching A Records
To fetch an "A" record for a domain:
```typescript
import { Smartdns } from '@push.rocks/smartdns';
2024-04-14 15:30:20 +00:00
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);
```
#### Fetching TXT Records
For "TXT" records:
```typescript
const txtRecords = await dnsManager.getRecordsTxt('example.com');
console.log(txtRecords);
```
2024-04-14 15:30:20 +00:00
### 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.
2017-07-18 13:45:06 +00:00
2018-05-13 14:21:15 +00:00
```typescript
2024-04-14 15:30:20 +00:00
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.');
}
2018-05-13 14:21:15 +00:00
```
2024-04-14 15:30:20 +00:00
### 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
}
```
### DNS Server Implementation
To implement a DNS server, `@push.rocks/smartdns` includes classes and methods to set up a UDP and HTTPS DNS server supporting DNSSEC.
#### Basic DNS Server Example
Here's a basic example of a UDP/HTTPS DNS server:
```typescript
import { DnsServer } from '@push.rocks/smartdns';
const dnsServer = new DnsServer({
httpsKey: 'path/to/key.pem',
httpsCert: 'path/to/cert.pem',
httpsPort: 443,
udpPort: 53,
dnssecZone: 'example.com',
});
dnsServer.registerHandler('*.example.com', ['A'], (question) => ({
name: question.name,
type: 'A',
class: 'IN',
ttl: 300,
data: '127.0.0.1',
}));
dnsServer.start().then(() => console.log('DNS Server started'));
```
### DNSSEC Support
`@push.rocks/smartdns` provides support for DNSSEC, including the generation, signing, and validation of DNS records.
#### DNSSEC Configuration
To configure DNSSEC for your DNS server:
```typescript
import { DnsServer } from '@push.rocks/smartdns';
const dnsServer = new DnsServer({
httpsKey: 'path/to/key.pem',
httpsCert: 'path/to/cert.pem',
httpsPort: 443,
udpPort: 53,
dnssecZone: 'example.com',
});
dnsServer.registerHandler('*.example.com', ['A'], (question) => ({
name: question.name,
type: 'A',
class: 'IN',
ttl: 300,
data: '127.0.0.1',
}));
dnsServer.start().then(() => console.log('DNS Server with DNSSEC started'));
```
This setup ensures that DNS records are signed and can be verified for authenticity.
### Handling DNS Queries Over Different Protocols
The library supports handling DNS queries over UDP and HTTPS.
#### Handling UDP Queries
UDP is the traditional means of DNS query transport.
```typescript
import { DnsServer } from '@push.rocks/smartdns';
import dgram from 'dgram';
dnsServer.registerHandler('*.example.com', ['A'], (question) => ({
name: question.name,
type: 'A',
class: 'IN',
ttl: 300,
data: '127.0.0.1',
}));
dnsServer.start().then(() => {
console.log('UDP DNS Server started on port', dnsServer.getOptions().udpPort);
});
const client = dgram.createSocket('udp4');
client.on('message', (msg, rinfo) => {
console.log(`Received ${msg} from ${rinfo.address}:${rinfo.port}`);
});
client.send(Buffer.from('example DNS query'), dnsServer.getOptions().udpPort, 'localhost');
```
#### Handling HTTPS Queries
DNS over HTTPS (DoH) is increasingly adopted for privacy and security.
```typescript
import { DnsServer } from '@push.rocks/smartdns';
import https from 'https';
import fs from 'fs';
const dnsServer = new DnsServer({
httpsKey: fs.readFileSync('path/to/key.pem'),
httpsCert: fs.readFileSync('path/to/cert.pem'),
httpsPort: 443,
udpPort: 53,
dnssecZone: 'example.com',
});
dnsServer.registerHandler('*.example.com', ['A'], (question) => ({
name: question.name,
type: 'A',
class: 'IN',
ttl: 300,
data: '127.0.0.1',
}));
dnsServer.start().then(() => console.log('HTTPS DNS Server started'));
const client = https.request({
hostname: 'localhost',
port: 443,
path: '/dns-query',
method: 'POST',
headers: {
'Content-Type': 'application/dns-message'
}
}, (res) => {
res.on('data', (d) => {
process.stdout.write(d);
});
});
client.on('error', (e) => {
console.error(e);
});
client.write(Buffer.from('example DNS query'));
client.end();
```
### Testing
To ensure that the DNS server behaves as expected, it is important to write tests for various scenarios.
#### DNS Server Tests
Here is an example of how to test the DNS server with TAP:
```typescript
import { expect, tap } from '@push.rocks/tapbundle';
import { DnsServer } from '@push.rocks/smartdns';
let dnsServer: DnsServer;
tap.test('should create an instance of DnsServer', async () => {
dnsServer = new DnsServer({
httpsKey: 'path/to/key.pem',
httpsCert: 'path/to/cert.pem',
httpsPort: 443,
udpPort: 53,
dnssecZone: 'example.com',
});
expect(dnsServer).toBeInstanceOf(DnsServer);
});
tap.test('should start the server', async () => {
await dnsServer.start();
expect(dnsServer.isRunning()).toBeTrue();
});
tap.test('should add a DNS handler', async () => {
dnsServer.registerHandler('*.example.com', ['A'], (question) => ({
name: question.name,
type: 'A',
class: 'IN',
ttl: 300,
data: '127.0.0.1',
}));
const response = dnsServer.processDnsRequest({
type: 'query',
id: 1,
flags: 0,
questions: [
{
name: 'test.example.com',
type: 'A',
class: 'IN',
},
],
answers: [],
});
expect(response.answers[0]).toEqual({
name: 'test.example.com',
type: 'A',
class: 'IN',
ttl: 300,
data: '127.0.0.1',
});
});
tap.test('should query the server over HTTP', async () => {
// Assuming fetch or any HTTP client is available
const query = dnsPacket.encode({
type: 'query',
id: 2,
flags: dnsPacket.RECURSION_DESIRED,
questions: [
{
name: 'test.example.com',
type: 'A',
class: 'IN',
},
],
});
const response = await fetch('https://localhost:443/dns-query', {
method: 'POST',
body: query,
headers: {
'Content-Type': 'application/dns-message',
}
});
expect(response.status).toEqual(200);
const responseData = await response.arrayBuffer();
const dnsResponse = dnsPacket.decode(Buffer.from(responseData));
expect(dnsResponse.answers[0]).toEqual({
name: 'test.example.com',
type: 'A',
class: 'IN',
ttl: 300,
data: '127.0.0.1',
});
});
tap.test('should stop the server', async () => {
await dnsServer.stop();
expect(dnsServer.isRunning()).toBeFalse();
});
await tap.start();
```
2024-04-14 15:30:20 +00:00
### 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
2017-07-18 13:45:06 +00:00
2024-04-14 15:30:20 +00:00
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
2024-04-14 15:30:20 +00:00
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
2024-04-14 15:30:20 +00:00
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.