The best way to control Claude Code, Codex and more from any computer or phone

main
ts 489 lines 16.7 KB
Raw
1 /**
2 * Node.js implementation of Effect's `Dns` service.
3 *
4 * Address lookups use the operating system resolver through `dns.lookup`,
5 * including the hosts file. Record queries and reverse lookups share one
6 * `dns.Resolver`. Interruption discards a query's result but cannot cancel
7 * that query; closing the scope cancels all pending queries.
8 *
9 * Unrepresentable records, such as invalid `Host.DomainName` values, are
10 * skipped. If every record is skipped, the query fails with `InvalidResponse`.
11 * `make` decodes Node.js's Latin-1 TXT and CAA strings as UTF-8. TLSA queries
12 * need Node.js 22.15 or 23.9 and later, and fail with `Unsupported` on runtimes
13 * without `resolveTlsa`. Other runtimes reuse `lookup`, `resolver`, and the
14 * conversion helpers to build their services.
15 *
16 * @stability experimental
17 * @since 4.0.0
18 */
19 import * as Arr from "effect/Array"
20 import * as Config from "effect/Config"
21 import * as Duration from "effect/Duration"
22 import * as Effect from "effect/Effect"
23 import * as Layer from "effect/Layer"
24 import * as Dns from "effect/net/Dns"
25 import * as Host from "effect/net/Host"
26 import * as NetAddress from "effect/net/NetAddress"
27 import * as Result from "effect/Result"
28 import * as NodeDns from "node:dns"
29
30 /**
31 * Options for the Node.js `Dns` service and `resolver`.
32 *
33 * **Details**
34 *
35 * `nameServers` replaces the system name servers, which are converted like
36 * `Dns.nameServerFromInput`, and an empty list keeps the system name servers.
37 * `timeout` is the time allowed for each attempt and `tries` the number of
38 * attempts per name server. Address lookups always use the operating system
39 * resolver and are not affected.
40 *
41 * `timeout` is rounded up to whole milliseconds and `tries` down to a whole
42 * number, and both are clamped to 1 through 2^31 - 1, so `Duration.infinity`
43 * uses the longest timeout the resolver supports.
44 *
45 * **Gotchas**
46 *
47 * Invalid name servers fail with a `NetAddress.NetAddressError` when the
48 * service is created, and so do IPv6 name servers with a scope ID, such as
49 * link-local addresses, because the resolver drops the scope.
50 *
51 * @stability experimental
52 * @category models
53 * @since 4.0.0
54 */
55 export interface Options {
56 readonly nameServers?: ReadonlyArray<NetAddress.IpAddressInput | NetAddress.InetAddressInput> | undefined
57 readonly timeout?: Duration.Input | undefined
58 readonly tries?: number | undefined
59 }
60
61 const reasons: Record<string, Dns.DnsErrorReason> = {
62 ENOTFOUND: "NotFound",
63 ENODATA: "NotFound",
64 ETIMEOUT: "Timeout",
65 // `getaddrinfo` reports SERVFAIL answers as `EAI_AGAIN`, and REFUSED,
66 // FORMERR, and NOTIMP answers alike as `EAI_FAIL`.
67 EAI_AGAIN: "Temporary",
68 EAI_FAIL: "Refused",
69 ESERVFAIL: "ServerFailure",
70 EREFUSED: "Refused",
71 ECONNREFUSED: "Refused",
72 EBADNAME: "BadName",
73 ENONAME: "BadName",
74 EBADFAMILY: "BadName",
75 EBADQUERY: "BadName",
76 EFORMERR: "InvalidResponse",
77 EBADRESP: "InvalidResponse",
78 ENOTIMP: "Unsupported"
79 }
80
81 /**
82 * Converts a failure of `node:dns` or of Bun's DNS functions to a
83 * `Dns.DnsError`, choosing the reason from the error's `code`.
84 *
85 * **Details**
86 *
87 * Bun prefixes c-ares codes with `DNS_`, such as `DNS_ENOTFOUND`; the prefix is
88 * ignored. Errors without a known code get the reason `Unknown`.
89 *
90 * @stability experimental
91 * @category converting
92 * @since 4.0.0
93 */
94 export const dnsErrorFromCause = (
95 cause: unknown,
96 method: Dns.DnsError["method"],
97 hostname: string,
98 recordType?: Dns.RecordType
99 ): Dns.DnsError => {
100 const code = typeof cause === "object" && cause !== null && "code" in cause
101 ? String(cause.code).replace(/^DNS_/, "")
102 : undefined
103 return new Dns.DnsError({
104 reason: (code !== undefined ? reasons[code] : undefined) ?? "Unknown",
105 method,
106 hostname,
107 recordType,
108 cause
109 })
110 }
111
112 // c-ares omits the root dot and represents the root name as an empty string.
113 const absoluteName = (name: string): string => {
114 if (name.endsWith(".")) {
115 let backslashes = 0
116 for (let i = name.length - 2; i >= 0 && name[i] === "\\"; i--) {
117 backslashes++
118 }
119 if (backslashes % 2 === 0) return name
120 }
121 return `${name}.`
122 }
123
124 /**
125 * Converts a name returned by a resolver to a fully qualified
126 * `Host.DomainName`, throwing when it is not a valid domain name.
127 *
128 * @stability experimental
129 * @category converting
130 * @since 4.0.0
131 */
132 export const domainNameFromResolverUnsafe = (name: string): Host.DomainName =>
133 Host.domainNameFromStringUnsafe(absoluteName(name))
134
135 const decoder = new TextDecoder()
136 const encoder = new TextEncoder()
137
138 const nameParts = /\\(\d{3})|\\(.)|[^\\]+|\\/gsu
139
140 /**
141 * Converts a name returned by a resolver to fully qualified text, for names
142 * that need not be host names, such as PTR targets and SOA mailboxes.
143 *
144 * **Details**
145 *
146 * Resolvers write bytes as `\DDD` escapes, c-ares in decimal (`radix` 10) and
147 * `Deno.resolveDns` in octal (`radix` 8), and escape special characters with
148 * a backslash, such as `\.` for a dot inside a label or `\(` for a
149 * parenthesis. Decoding the bytes as UTF-8 and removing the escapes gives the
150 * text of the name, keeping only the `\.` and `\\` escapes.
151 *
152 * @stability experimental
153 * @category converting
154 * @since 4.0.0
155 */
156 export const nameTextFromResolver = (name: string, radix: 8 | 10 = 10): string => {
157 if (!name.includes("\\")) return absoluteName(name)
158 const bytes: Array<number> = []
159 for (const [part, digits, escaped] of name.matchAll(nameParts)) {
160 if (digits !== undefined) {
161 const byte = Number.parseInt(digits, radix)
162 if (byte === 46 || byte === 92) bytes.push(92)
163 bytes.push(byte)
164 } else if (escaped !== undefined) {
165 if (escaped === "." || escaped === "\\") bytes.push(92)
166 bytes.push(...encoder.encode(escaped))
167 } else {
168 bytes.push(...encoder.encode(part))
169 }
170 }
171 return absoluteName(decoder.decode(Uint8Array.from(bytes)))
172 }
173
174 /**
175 * Converts a number of seconds that a resolver reports as a signed 32-bit
176 * integer, such as the SOA refresh, retry, and expire intervals, to a
177 * `Duration`.
178 *
179 * @stability experimental
180 * @category converting
181 * @since 4.0.0
182 */
183 export const secondsFromInt32 = (value: number): Duration.Duration => Duration.seconds(value >>> 0)
184
185 /**
186 * Decodes a string that holds one byte per character as UTF-8.
187 *
188 * **Details**
189 *
190 * Node.js and `Deno.resolveDns` decode each byte of TXT and CAA character
191 * strings as one Latin-1 character; decoding the bytes as UTF-8 matches other
192 * runtimes. Strings with only ASCII characters are returned unchanged.
193 *
194 * @stability experimental
195 * @category converting
196 * @since 4.0.0
197 */
198 export const utf8FromLatin1 = (value: string): string =>
199 // oxlint-disable-next-line no-control-regex
200 /[^\x00-\x7f]/.test(value) ? decoder.decode(Uint8Array.from(value, (character) => character.charCodeAt(0))) : value
201
202 /**
203 * Converts the entries of a resolver's answer to a query for `name` to records
204 * of a record type, skipping entries whose data cannot be represented, such as
205 * names that are not valid `Host.DomainName` values.
206 *
207 * **Details**
208 *
209 * When the answer has entries but every one is skipped, the conversion fails
210 * with an `InvalidResponse` error whose cause is the first entry's failure,
211 * rather than returning no records, which would be reported as `NotFound`.
212 *
213 * @stability experimental
214 * @category converting
215 * @since 4.0.0
216 */
217 export const recordsFromResolver = <T extends Dns.RecordType, A>(
218 name: string,
219 type: T,
220 entries: ReadonlyArray<A>,
221 fields: (entry: A) => Dns.RecordFields<T>
222 ): Result.Result<Array<Dns.RecordFor<T>>, Dns.DnsError> => {
223 const records: Array<Dns.RecordFor<T>> = []
224 let skipped: { readonly failure: unknown } | undefined
225 for (const entry of entries) {
226 const result = Result.try(() => Dns.makeRecordUnsafe(type, fields(entry)))
227 if (Result.isSuccess(result)) {
228 records.push(result.success)
229 } else {
230 skipped ??= result
231 }
232 }
233 return records.length === 0 && skipped !== undefined
234 ? Result.fail(
235 new Dns.DnsError({
236 reason: "InvalidResponse",
237 method: "resolve",
238 hostname: name,
239 recordType: type,
240 cause: skipped.failure
241 })
242 )
243 : Result.succeed(records)
244 }
245
246 const queries: {
247 readonly [K in Dns.RecordType]: (
248 resolver: NodeDns.promises.Resolver,
249 name: string
250 ) => Promise<Result.Result<Array<Dns.DnsRecord>, Dns.DnsError>>
251 } = {
252 A: async (resolver, name) =>
253 recordsFromResolver(name, "A", await resolver.resolve4(name), (address) => ({
254 address: NetAddress.ipFromStringUnsafe(address) as NetAddress.Ipv4Address
255 })),
256 AAAA: async (resolver, name) =>
257 recordsFromResolver(name, "AAAA", await resolver.resolve6(name), (address) => ({
258 address: NetAddress.ipFromStringUnsafe(address) as NetAddress.Ipv6Address
259 })),
260 CAA: async (resolver, name) =>
261 recordsFromResolver(name, "CAA", await resolver.resolveCaa(name), (caa) => {
262 const tag = Object.keys(caa).find((key) => key !== "critical" && key !== "type")
263 if (tag === undefined) throw new Error("CAA record without a property tag")
264 // Only the issuer critical flag (bit 7) is defined; other flag bits are reserved.
265 return { critical: (caa.critical & 0x80) !== 0, tag, value: String((caa as any)[tag]) }
266 }),
267 CNAME: async (resolver, name) =>
268 recordsFromResolver(name, "CNAME", await resolver.resolveCname(name), (target) => ({
269 target: domainNameFromResolverUnsafe(target)
270 })),
271 MX: async (resolver, name) =>
272 recordsFromResolver(name, "MX", await resolver.resolveMx(name), (mx) => ({
273 exchange: domainNameFromResolverUnsafe(mx.exchange),
274 priority: mx.priority
275 })),
276 NAPTR: async (resolver, name) =>
277 recordsFromResolver(name, "NAPTR", await resolver.resolveNaptr(name), (naptr) => ({
278 order: naptr.order,
279 preference: naptr.preference,
280 flags: naptr.flags,
281 service: naptr.service,
282 regexp: naptr.regexp,
283 replacement: domainNameFromResolverUnsafe(naptr.replacement)
284 })),
285 NS: async (resolver, name) =>
286 recordsFromResolver(name, "NS", await resolver.resolveNs(name), (host) => ({
287 host: domainNameFromResolverUnsafe(host)
288 })),
289 PTR: async (resolver, name) =>
290 recordsFromResolver(name, "PTR", await resolver.resolvePtr(name), (host) => ({
291 host: nameTextFromResolver(host)
292 })),
293 SOA: async (resolver, name) =>
294 recordsFromResolver(name, "SOA", [await resolver.resolveSoa(name)], (soa) => ({
295 primary: domainNameFromResolverUnsafe(soa.nsname),
296 admin: nameTextFromResolver(soa.hostmaster),
297 serial: soa.serial,
298 refresh: secondsFromInt32(soa.refresh),
299 retry: secondsFromInt32(soa.retry),
300 expire: secondsFromInt32(soa.expire),
301 minimum: Duration.seconds(soa.minttl)
302 })),
303 SRV: async (resolver, name) =>
304 recordsFromResolver(name, "SRV", await resolver.resolveSrv(name), (srv) => ({
305 target: domainNameFromResolverUnsafe(srv.name),
306 port: srv.port,
307 priority: srv.priority,
308 weight: srv.weight
309 })),
310 // `resolveTlsa` was added in Node.js 22.15 and 23.9; Bun and Deno lack it.
311 TLSA: async (resolver, name) =>
312 typeof resolver.resolveTlsa === "function"
313 ? recordsFromResolver(name, "TLSA", await resolver.resolveTlsa(name), (tlsa) => ({
314 certUsage: tlsa.certUsage,
315 selector: tlsa.selector,
316 matchingType: tlsa.match,
317 data: new Uint8Array(tlsa.data)
318 }))
319 : Result.fail(
320 new Dns.DnsError({ reason: "Unsupported", method: "resolve", hostname: name, recordType: "TLSA" })
321 ),
322 TXT: async (resolver, name) =>
323 recordsFromResolver(name, "TXT", await resolver.resolveTxt(name), (chunks) => ({
324 chunks: chunks as unknown as Arr.NonEmptyReadonlyArray<string>
325 }))
326 }
327
328 /**
329 * Converts an IP family to the numeric family used by `dns.lookup`, with `0`
330 * for addresses of either family.
331 *
332 * @stability experimental
333 * @category converting
334 * @since 4.0.0
335 */
336 export const toFamily = (family: NetAddress.IpFamily | undefined): 0 | 4 | 6 =>
337 family === "IPv4" ? 4 : family === "IPv6" ? 6 : 0
338
339 const stripZone = (address: string): string => {
340 const separator = address.indexOf("%")
341 return separator === -1 ? address : address.slice(0, separator)
342 }
343
344 /**
345 * Converts the entries returned by an address lookup, such as `dns.lookup`
346 * with `all: true`, to IP addresses, keeping their order.
347 *
348 * **Details**
349 *
350 * IPv6 zones are dropped, and addresses that cannot be parsed are skipped.
351 *
352 * @stability experimental
353 * @category converting
354 * @since 4.0.0
355 */
356 export const addressesFromLookup = (
357 entries: ReadonlyArray<{ readonly address: string }>
358 ): Array<NetAddress.IpAddress> =>
359 Arr.filterMap(entries, (entry) => Result.try(() => NetAddress.ipFromStringUnsafe(stripZone(entry.address))))
360
361 /**
362 * Looks up the addresses of a host name with `dns.lookup`, keeping the order
363 * returned by the operating system resolver.
364 *
365 * @stability experimental
366 * @category resolving
367 * @since 4.0.0
368 */
369 export const lookup = (
370 host: string,
371 family?: NetAddress.IpFamily | undefined
372 ): Effect.Effect<Array<NetAddress.IpAddress>, Dns.DnsError> =>
373 Effect.tryPromise({
374 // `verbatim` keeps the system order on Node versions without `order`.
375 try: () =>
376 NodeDns.promises.lookup(host, { all: true, family: toFamily(family), order: "verbatim", verbatim: true }),
377 catch: (cause) => dnsErrorFromCause(cause, "lookup", host)
378 }).pipe(Effect.map(addressesFromLookup))
379
380 // Clamp resolver options to positive signed 32-bit integers; NaN becomes 1.
381 const resolverInt = (value: number): number => value >= 1 ? Math.min(value, 2 ** 31 - 1) : 1
382
383 /**
384 * Creates a function that queries DNS records with the runtime's `node:dns`
385 * module.
386 *
387 * **Details**
388 *
389 * All queries share one `dns.Resolver`, which is cancelled when the scope
390 * closes. Names in records are fully qualified, and TXT and CAA character
391 * strings are returned as the runtime decodes them, without the UTF-8
392 * correction that `make` applies for Node.js. Records are converted with
393 * `recordsFromResolver`.
394 *
395 * @stability experimental
396 * @category constructors
397 * @since 4.0.0
398 */
399 export const resolver = Effect.fnUntraced(function*(options?: Options) {
400 const resolverOptions: NodeDns.ResolverOptions = {
401 ...(options?.timeout !== undefined && { timeout: resolverInt(Math.ceil(Duration.toMillis(options.timeout))) }),
402 ...(options?.tries !== undefined && { tries: resolverInt(Math.floor(options.tries)) })
403 }
404 const nameServers: Array<NetAddress.InetAddress> = []
405 for (const input of options?.nameServers ?? []) {
406 const server = yield* Effect.fromResult(Dns.nameServerFromInput(input))
407 if (NetAddress.isInetAddressV6(server) && server.scopeId !== 0) {
408 return yield* new NetAddress.NetAddressError({
409 input,
410 message: "IPv6 name servers with a scope ID are not supported"
411 })
412 }
413 nameServers.push(server)
414 }
415
416 const resolver = yield* Effect.acquireRelease(
417 Effect.sync(() => {
418 const resolver = new NodeDns.promises.Resolver(resolverOptions)
419 if (nameServers.length > 0) {
420 resolver.setServers(
421 nameServers.map(NetAddress.formatInet)
422 )
423 }
424 return resolver
425 }),
426 (resolver) => Effect.sync(() => resolver.cancel())
427 )
428
429 return (name: string, type: Dns.RecordType): Effect.Effect<Array<Dns.DnsRecord>, Dns.DnsError> =>
430 Effect.tryPromise({
431 try: () => queries[type](resolver, name),
432 catch: (cause) => dnsErrorFromCause(cause, "resolve", name, type)
433 }).pipe(Effect.flatMap(Effect.fromResult))
434 })
435
436 const utf8Strings = (record: Dns.DnsRecord): Dns.DnsRecord => {
437 switch (record._tag) {
438 case "TXT":
439 return Dns.makeRecordUnsafe("TXT", {
440 chunks: Arr.map(record.chunks, utf8FromLatin1)
441 })
442 case "CAA":
443 return Dns.makeRecordUnsafe("CAA", {
444 critical: record.critical,
445 tag: record.tag,
446 value: utf8FromLatin1(record.value)
447 })
448 default:
449 return record
450 }
451 }
452
453 /**
454 * Creates a Node.js `Dns` service whose resolver lives as long as the scope.
455 *
456 * @stability experimental
457 * @category constructors
458 * @since 4.0.0
459 */
460 export const make = Effect.fnUntraced(function*(options?: Options) {
461 const resolve = yield* resolver(options)
462 return Dns.make({
463 lookup,
464 resolve: (name, type) => Effect.map(resolve(name, type), Arr.map(utf8Strings))
465 })
466 })
467
468 /**
469 * Layer that provides the Node.js `Dns` service using the system resolver
470 * configuration.
471 *
472 * @stability experimental
473 * @category layers
474 * @since 4.0.0
475 */
476 export const layer: Layer.Layer<Dns.Dns> = Layer.effect(Dns.Dns, Effect.orDie(make()))
477
478 /**
479 * Creates a layer that provides the Node.js `Dns` service with options read
480 * from configuration.
481 *
482 * @stability experimental
483 * @category layers
484 * @since 4.0.0
485 */
486 export const layerConfig = (
487 options: Config.Wrap<Options>
488 ): Layer.Layer<Dns.Dns, Config.ConfigError | NetAddress.NetAddressError> =>
489 Layer.effect(Dns.Dns, Effect.flatMap(Config.unwrap(options), make))