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 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/**
 * PrivacyGuard DNS - API Reference
 * 
 * This document describes the available APIs for developers
 * who want to integrate with PrivacyGuard DNS services.
 * 
 * Version: 1.0.0
 * Last Updated: 2025-01-14
 */

# Table of Contents

1. [Overview](#overview)
2. [DNS-over-HTTPS (DoH)](#dns-over-https-doh)
3. [DNS-over-TLS (DoT)](#dns-over-tls-dot)
4. [REST API](#rest-api)
5. [Authentication](#authentication)
6. [Rate Limits](#rate-limits)
7. [Error Handling](#error-handling)
8. [Examples](#examples)

---

## Overview

PrivacyGuard DNS provides several APIs for developers:

| API Type | Protocol | Port | Use Case |
|----------|----------|------|----------|
| DoH | HTTPS | 443 | Encrypted DNS queries from web apps |
| DoT | TLS | 853 | Encrypted DNS queries from apps |
| REST API | HTTPS | 443 | User management, statistics |

---

## DNS-over-HTTPS (DoH)

### Endpoint

```
https://dns.nextdns.io/dns-query
```

### Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `name` | string | Yes | Domain name to resolve |
| `type` | string | No | Record type (A, AAAA, MX, etc.) Default: A |
| `ct` | string | No | Content type (application/dns-json) |

### Request Example

```javascript
// JavaScript/TypeScript Example
async function queryDNS(name, type = 'A') {
    const url = `https://dns.nextdns.io/dns-query?name=${encodeURIComponent(name)}&type=${type}`;
    
    const response = await fetch(url, {
        headers: {
            'Accept': 'application/dns-json'
        }
    });
    
    return response.json();
}

// Usage
queryDNS('example.com', 'A')
    .then(data => console.log(data))
    .catch(error => console.error(error));
```

### Response Format

```json
{
    "Status": 0,
    "TC": false,
    "RD": true,
    "RA": true,
    "AD": true,
    "CD": false,
    "Question": [
        {
            "name": "example.com.",
            "type": 1,
            "class": 1
        }
    ],
    "Answer": [
        {
            "name": "example.com.",
            "type": 1,
            "class": 1,
            "TTL": 3600,
            "data": "93.184.216.34"
        }
    ],
    "Authority": []
}
```

### Response Codes

| Code | Description |
|------|-------------|
| 0 | No error |
| 1 | Format error |
| 2 | Server failure |
| 3 | Name error (domain not found) |
| 4 | Not implemented |
| 5 | Refused |

---

## DNS-over-TLS (DoT)

### Endpoint

```
dns.nextdns.io:853
```

### Connection Example

```javascript
// Node.js DoT Client Example
const tls = require('tls');

const options = {
    host: 'dns.nextdns.io',
    port: 853,
    rejectUnauthorized: true
};

const socket = tls.connect(options, () => {
    console.log('Connected to DoT server');
    
    // DNS query in wire format
    const query = Buffer.from([
        0x00, 0x2c, // Transaction ID
        0x01, 0x00, // Flags (RD=1)
        0x00, 0x01, // Question count
        0x00, 0x00, // Answer count
        0x00, 0x00, // Authority count
        0x00, 0x00, // Additional count
        // Question section
        0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65,
        0x03, 0x63, 0x6f, 0x6d, 0x00,
        0x00, 0x01, // Type A
        0x00, 0x01  // Class IN
    ]);
    
    socket.write(query);
});

socket.on('data', (data) => {
    console.log('Response:', data.toString('hex'));
    socket.end();
});

socket.on('error', (error) => {
    console.error('Error:', error);
});
```

---

## REST API

### Base URL

```
https://api.privacyguard.dns/v1
```

### Authentication

All API requests require authentication using API keys.

```http
Authorization: Bearer YOUR_API_KEY
```

### Endpoints

#### Get Account Information

```http
GET /account
Authorization: Bearer YOUR_API_KEY
```

**Response:**

```json
{
    "id": "acc_123456789",
    "email": "user@example.com",
    "plan": "free",
    "created_at": "2025-01-01T00:00:00Z",
    "quota": {
        "queries": 0,
        "limit": 300000
    }
}
```

#### Get Usage Statistics

```http
GET /statistics
Authorization: Bearer YOUR_API_KEY

Query Parameters:
- start_date: ISO 8601 date
- end_date: ISO 8601 date
- granularity: hourly | daily | weekly
```

**Response:**

```json
{
    "period": {
        "start": "2025-01-01T00:00:00Z",
        "end": "2025-01-14T23:59:59Z"
    },
    "data": {
        "total_queries": 1250000,
        "blocked_ads": 450000,
        "blocked_trackers": 180000,
        "blocked_malware": 50000,
        "queries_by_country": {
            "US": 450000,
            "DE": 250000,
            "GB": 150000
        }
    }
}
```

#### Get Blocked Domains

```http
GET /blocked-domains
Authorization: Bearer YOUR_API_KEY

Query Parameters:
- page: 1
- limit: 100
- category: ads | trackers | malware
```

**Response:**

```json
{
    "data": [
        {
            "domain": "ads.example.com",
            "category": "ads",
            "blocked_at": "2025-01-14T10:00:00Z",
            "block_count": 15420
        }
    ],
    "pagination": {
        "page": 1,
        "limit": 100,
        "total": 12500
    }
}
```

#### Create Custom Blocklist

```http
POST /custom-blocklists
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json

{
    "name": "My Blocklist",
    "domains": [
        "ads.example.com",
        "trackers.example.net"
    ]
}
```

**Response:**

```json
{
    "id": "bl_123456789",
    "name": "My Blocklist",
    "domain_count": 2,
    "created_at": "2025-01-14T10:00:00Z"
}
```

---

## Authentication

### Obtaining API Keys

1. Create an account at [https://privacyguard.dns](https://privacyguard.dns)
2. Navigate to Settings > API
3. Generate a new API key

### Using API Keys

```bash
# Using curl
curl -H "Authorization: Bearer YOUR_API_KEY" \
     https://api.privacyguard.dns/v1/account

# Using JavaScript
const apiKey = 'YOUR_API_KEY';
const response = await fetch('https://api.privacyguard.dns/v1/account', {
    headers: {
        'Authorization': `Bearer ${apiKey}`
    }
});
```

---

## Rate Limits

| Plan | Requests/Day | Requests/Minute |
|------|--------------|-----------------|
| Free | 1,000 | 10 |
| Pro | 100,000 | 100 |
| Enterprise | Unlimited | 1,000 |

### Rate Limit Headers

```http
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200
```

---

## Error Handling

### Error Response Format

```json
{
    "error": {
        "code": "RATE_LIMIT_EXCEEDED",
        "message": "You have exceeded the rate limit",
        "details": {
            "retry_after": 60
        }
    }
}
```

### Error Codes

| Code | HTTP Status | Description |
|------|-------------|-------------|
| AUTH_REQUIRED | 401 | Authentication required |
| INVALID_API_KEY | 401 | Invalid or expired API key |
| RATE_LIMIT_EXCEEDED | 429 | Rate limit exceeded |
| QUOTA_EXCEEDED | 403 | Monthly quota exceeded |
| INVALID_REQUEST | 400 | Invalid request parameters |
| SERVER_ERROR | 500 | Internal server error |

---

## Examples

### Complete DoH Example with Error Handling

```javascript
class PrivacyGuardDNS {
    constructor(apiKey = null) {
        this.baseUrl = 'https://dns.nextdns.io/dns-query';
        this.apiKey = apiKey;
    }
    
    async query(name, type = 'A') {
        try {
            const url = `${this.baseUrl}?name=${encodeURIComponent(name)}&type=${type}`;
            
            const response = await fetch(url, {
                headers: {
                    'Accept': 'application/dns-json'
                }
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            
            if (data.Status !== 0) {
                throw new Error(`DNS error: ${this.getDNSErrorMessage(data.Status)}`);
            }
            
            return {
                domain: name,
                type: type,
                answers: data.Answer?.map(record => ({
                    name: record.name,
                    type: record.type,
                    ttl: record.TTL,
                    data: record.data
                })) || []
            };
            
        } catch (error) {
            console.error('DNS Query Error:', error);
            throw error;
        }
    }
    
    getDNSErrorMessage(status) {
        const errors = {
            1: 'Format error',
            2: 'Server failure',
            3: 'Name error (domain not found)',
            4: 'Not implemented',
            5: 'Refused'
        };
        return errors[status] || 'Unknown error';
    }
}

// Usage
const dns = new PrivacyGuardDNS();

async function test() {
    try {
        const result = await dns.query('example.com', 'A');
        console.log('DNS Result:', result);
    } catch (error) {
        console.error('Failed to query DNS:', error.message);
    }
}

test();
```

### Python DoH Example

```python
import requests

class PrivacyGuardDNS:
    def __init__(self):
        self.base_url = "https://dns.nextdns.io/dns-query"
    
    def query(self, name, record_type='A'):
        params = {
            'name': name,
            'type': record_type
        }
        
        headers = {
            'Accept': 'application/dns-json'
        }
        
        response = requests.get(
            self.base_url,
            params=params,
            headers=headers
        )
        
        response.raise_for_status()
        return response.json()

# Usage
dns = PrivacyGuardDNS()
result = dns.query('example.com', 'A')
print(result)
```

---

## SDKs and Libraries

| Language | Library | Repository |
|----------|---------|------------|
| JavaScript/TypeScript | @privacyguard/dns-sdk | github.com/privacyguard/dns-sdk-js |
| Python | privacyguard-dns | github.com/privacyguard/dns-sdk-python |
| Go | privacyguard-dns | github.com/privacyguard/dns-sdk-go |
| Rust | privacyguard-dns | github.com/privacyguard/dns-sdk-rust |

---

## Support

- **Documentation**: [docs.privacyguard.dns](https://docs.privacyguard.dns)
- **Email**: api-support@privacyguard.dns
- **GitHub Issues**: [github.com/privacyguard/dns/issues](https://github.com/privacyguard/dns/issues)

---

*This documentation is subject to change. Last updated: 2025-01-14*