2023-08-17 19:50:35 +05:30
|
|
|
import type { DnsClient } from "@waku/interfaces";
|
2023-10-20 16:36:47 +05:30
|
|
|
import { Logger } from "@waku/utils";
|
2023-03-14 10:10:38 +05:30
|
|
|
import { bytesToUtf8 } from "@waku/utils/bytes";
|
2025-03-19 19:43:41 +11:00
|
|
|
import DnsOverHttpResolver from "dns-over-http-resolver";
|
2022-01-13 11:33:26 +11:00
|
|
|
|
2023-10-20 16:36:47 +05:30
|
|
|
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.
|
|
|
|
|
*
|
|
|
|
|
* @throws {code: string} If DNS query fails.
|
|
|
|
|
*/
|
2025-03-19 19:43:41 +11:00
|
|
|
public static async create(): Promise<DnsOverHttps> {
|
|
|
|
|
return new DnsOverHttps();
|
2023-04-03 15:59:07 +10:00
|
|
|
}
|
|
|
|
|
|
2025-03-19 19:43:41 +11:00
|
|
|
private constructor(private resolver = new DnsOverHttpResolver()) {}
|
2022-01-13 11:33:26 +11:00
|
|
|
|
2022-03-01 16:51:21 +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-03-01 16:51:21 +11:00
|
|
|
*/
|
2024-07-19 15:58:17 +05:30
|
|
|
public async resolveTXT(domain: string): Promise<string[]> {
|
2022-07-19 15:43:35 +10:00
|
|
|
let answers;
|
|
|
|
|
try {
|
2025-03-19 19:43:41 +11:00
|
|
|
answers = await this.resolver.resolveTxt(domain);
|
2022-07-19 15:43:35 +10:00
|
|
|
} catch (error) {
|
2023-10-20 16:36:47 +05:30
|
|
|
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
|
|
|
|
|
|
|
|
const result: string[] = [];
|
|
|
|
|
|
2025-03-19 19:43:41 +11:00
|
|
|
answers.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;
|
|
|
|
|
}
|
|
|
|
|
}
|