Skip to content

Instantly share code, notes, and snippets.

@zoonderkins
Last active December 12, 2019 12:44
Show Gist options
  • Save zoonderkins/2679be93fe104f0afce2a9fa0956167e to your computer and use it in GitHub Desktop.
Save zoonderkins/2679be93fe104f0afce2a9fa0956167e to your computer and use it in GitHub Desktop.
淺談-DNS-over-HTTPS.md

DNS-over-HTTPS Nodejs example

const fetch = require('node-fetch')
const Packet = require('native-dns-packet')

class DoH {
  constructor(provider) {
    // this.provider = this.provider
    // this.uri = this.providers.value[provider]
  }
  providers = {
    value: {
      blahdns: 'https://doh-jp.blahdns.com/dns-query',
      google: 'https://dns.google/resolve'
    },
    writable: false
  }

  setProvider = provider => {
    this.provider = provider
    //console.log(this.provider)
    if (this.provider === provider) {
      this.uri = this.providers.value[provider]
      return
    }
    if (
      this.providers.value.toString() !=
        Object.keys(this.providers.value).toString() ||
      'undefined'
    ) {
      throw new Error('We only support blahdns & Google DNS')
    }
  }

  getDomainType = domainType => {
    let type = 0
    switch (domainType) {
      case 'AAAA':
        type = 28
        break
      case 'CNAME':
        type = 5
        break
      default:
        type = 1
        break
    }
    return type
  }

  resolve = async (domainName, domainType) => {
    let a = 0
    let type = this.getDomainType(domainType)
    let dnsPacket = new Packet()
    let dnsBuf = Buffer.alloc(128)
    dnsPacket.question.push({
      name: domainName,
      type,
      class: 1
    })
    Packet.write(dnsBuf, dnsPacket)

    // let query = ` ${this.uri}?dns=${dnsBuf
    //   .toString('base64')
    //   .replace(/=+/, '')}`
    let query = `${this.uri}?name=${domainName}&type=${domainType}`
    console.log(query)
    a = await fetch(query, {
      method: 'get'
    }).then(res => res.json())

    return a
  }
}

const newRequest = new DoH()

newRequest.setProvider('google')
newRequest.resolve('blahdns.com', 'AAAA').then(console.log)

package.json

{
  "name": "dns-over-https-101",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "native-dns-packet": "^0.1.1",
    "node-fetch": "^2.6.0"
  }
}

https://docs.google.com/presentation/d/1ikVw_UXvBS2cz9w94OUFqJ29NasOzmy0pUKCntijYKM/edit?usp=sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment