js-waku/packages/discovery/src/dns/dns_over_https.ts

84 lines
2.0 KiB
TypeScript
Raw Normal View History

import type { DnsClient } from "@waku/interfaces";
import { Logger } from "@waku/utils";
import { bytesToUtf8 } from "@waku/utils/bytes";
import { Endpoint, query, wellknown } from "dns-query";
2022-01-13 11:33:26 +11:00
const log = new Logger("dns-over-https");
2022-01-13 11:33:26 +11:00
export class DnsOverHttps implements DnsClient {
/**
* Create new Dns-Over-Http DNS client.
*
2022-07-19 15:43:35 +10:00
* @param endpoints The endpoints for Dns-Over-Https queries;
* Defaults to using dns-query's API..
2022-07-19 15:43:35 +10:00
* @param retries Retries if a given endpoint fails.
2022-01-13 11:33:26 +11:00
*
* @throws {code: string} If DNS query fails.
*/
public static async create(
endpoints?: Endpoint[],
retries?: number
): Promise<DnsOverHttps> {
const _endpoints = endpoints ?? (await wellknown.endpoints("doh"));
return new DnsOverHttps(_endpoints, retries);
}
private constructor(
private endpoints: Endpoint[],
private retries: number = 3
2022-01-13 11:33:26 +11:00
) {}
/**
* Resolves a TXT record
*
* @param domain The domain name
*
2022-07-19 15:43:35 +10:00
* @throws if the query fails
*/
2022-01-13 11:33:26 +11:00
async resolveTXT(domain: string): Promise<string[]> {
2022-07-19 15:43:35 +10:00
let answers;
try {
const res = await query(
{
question: { type: "TXT", name: domain }
2022-07-19 15:43:35 +10:00
},
{
endpoints: this.endpoints,
retries: this.retries
}
2022-07-19 15:43:35 +10:00
);
answers = res.answers;
} catch (error) {
log.error("query failed: ", error);
2022-07-19 15:43:35 +10:00
throw new Error("DNS query failed");
}
2022-01-13 11:33:26 +11:00
2022-07-19 15:43:35 +10:00
if (!answers) throw new Error(`Could not resolve ${domain}`);
2022-01-13 11:33:26 +11:00
2022-07-19 15:43:35 +10:00
const data = answers.map((a) => a.data) as
| Array<string | Uint8Array>
| Array<Array<string | Uint8Array>>;
2022-01-13 11:33:26 +11:00
const result: string[] = [];
data.forEach((d) => {
2022-02-04 14:12:00 +11:00
if (typeof d === "string") {
2022-01-13 11:33:26 +11:00
result.push(d);
} else if (Array.isArray(d)) {
d.forEach((sd) => {
2022-02-04 14:12:00 +11:00
if (typeof sd === "string") {
2022-01-13 11:33:26 +11:00
result.push(sd);
} else {
2022-02-16 14:08:48 +11:00
result.push(bytesToUtf8(sd));
2022-01-13 11:33:26 +11:00
}
});
} else {
2022-02-16 14:08:48 +11:00
result.push(bytesToUtf8(d));
2022-01-13 11:33:26 +11:00
}
});
return result;
}
}