@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 227 lines 8.42 KB
Raw
1 /**
2 * TXT propagation checks.
3 *
4 * Public recursive resolvers are a poor oracle: they cache negative
5 * answers for the zone's SOA minimum (30 minutes is common) and old
6 * record sets past their TTL, so a challenge value published a moment ago
7 * can stay invisible for far longer than the CA takes to validate. Where
8 * `node:dns` is available (deploy time, Fly Machines) the check therefore
9 * asks the zone's **authoritative** nameservers directly — the same
10 * servers the CA asks. Networks can intercept port 53, so DNS over HTTPS
11 * also checks for the exact challenge value. A stale recursive cache must
12 * not veto a positive answer; the CA performs its own validation.
13 */
14 import * as Duration from "effect/Duration";
15 import * as Effect from "effect/Effect";
16 import * as HttpClient from "effect/http/HttpClient";
17 import * as HttpClientRequest from "effect/http/HttpClientRequest";
18 import * as Schedule from "effect/Schedule";
19 import { DnsPropagationTimeout } from "./Errors.ts";
20
21 export interface PropagationOptions {
22 /**
23 * Wait before the first lookup to avoid caching an unpublished record.
24 * Outside the polling budget. Cloudflare defaults to 60 seconds.
25 * @default "0 seconds"
26 */
27 readonly initialDelay?: Duration.Input | undefined;
28 /**
29 * Extra wait after the record is seen (or, for solvers that skip the
30 * check, the whole wait): anycast edges lag the first one that answers.
31 * @default "5 seconds"
32 */
33 readonly delay?: Duration.Input | undefined;
34 /**
35 * DNS-over-HTTPS JSON endpoints to use instead of automatic discovery.
36 * When supplied, every resolver must return the record. Automatic lookup
37 * accepts all discovered nameservers or any default DoH resolver.
38 * @default Cloudflare (1.1.1.1) and Google public DNS
39 */
40 readonly resolvers?: ReadonlyArray<string> | undefined;
41 /** Polling budget. @default "45 seconds" */
42 readonly timeout?: Duration.Input | undefined;
43 /** Polling interval. @default "3 seconds" */
44 readonly interval?: Duration.Input | undefined;
45 }
46
47 export const DEFAULT_PROPAGATION_DELAY: Duration.Input = "5 seconds";
48
49 /** Sleep `options.delay` (default 5 seconds). */
50 export const propagationDelay = (options: PropagationOptions = {}): Effect.Effect<void> =>
51 Effect.sleep(options.delay ?? DEFAULT_PROPAGATION_DELAY);
52
53 // =============================================================================
54 // Authoritative lookup (node:dns where available)
55 // =============================================================================
56
57 interface NodeDns {
58 readonly resolveNs: (name: string) => Promise<string[]>;
59 readonly resolve4: (name: string) => Promise<string[]>;
60 readonly Resolver: new () => {
61 setServers(servers: string[]): void;
62 resolveTxt(name: string): Promise<string[][]>;
63 };
64 }
65
66 const nodeDns: Effect.Effect<NodeDns | undefined> = Effect.tryPromise(
67 () => import("node:dns/promises") as unknown as Promise<NodeDns>,
68 ).pipe(
69 Effect.map((mod) =>
70 typeof mod?.Resolver === "function" && typeof mod.resolveNs === "function" ? mod : undefined,
71 ),
72 Effect.orElseSucceed(() => undefined),
73 );
74
75 /** The zone apex's nameserver IPv4s for `fqdn`, or `[]` when unknown. */
76 const authoritativeServers = (dns: NodeDns, fqdn: string): Effect.Effect<ReadonlyArray<string>> =>
77 Effect.gen(function* () {
78 const labels = fqdn.replace(/\.$/, "").split(".");
79 for (let i = 0; i < labels.length - 1; i++) {
80 const candidate = labels.slice(i).join(".");
81 const names = yield* Effect.tryPromise(() => dns.resolveNs(candidate)).pipe(
82 Effect.orElseSucceed(() => [] as string[]),
83 );
84 if (names.length === 0) continue;
85 const addresses = yield* Effect.forEach(
86 names,
87 (name) =>
88 Effect.tryPromise(() => dns.resolve4(name)).pipe(
89 Effect.orElseSucceed(() => [] as string[]),
90 ),
91 { concurrency: "unbounded" },
92 );
93 return addresses.flat();
94 }
95 return [];
96 });
97
98 /** TXT values requested from one nameserver (port 53 may be intercepted). */
99 const resolveTxtAt = (
100 dns: NodeDns,
101 server: string,
102 fqdn: string,
103 ): Effect.Effect<ReadonlyArray<string>> =>
104 Effect.gen(function* () {
105 const resolver = yield* Effect.sync(() => new dns.Resolver());
106 yield* Effect.sync(() => resolver.setServers([server]));
107 const records = yield* Effect.tryPromise(() => resolver.resolveTxt(fqdn));
108 return records.map((chunks) => chunks.join(""));
109 }).pipe(
110 Effect.timeout("3 seconds"),
111 Effect.orElseSucceed(() => [] as ReadonlyArray<string>),
112 );
113
114 export const DEFAULT_RESOLVERS: ReadonlyArray<string> = [
115 "https://cloudflare-dns.com/dns-query",
116 "https://dns.google/resolve",
117 ];
118
119 interface DohAnswer {
120 readonly type?: number;
121 readonly data?: string;
122 }
123
124 const unquote = (data: string): string =>
125 (data.match(/"((?:[^"\\]|\\.)*)"/g) ?? [data])
126 .map((part) => part.replace(/^"|"$/g, "").replace(/\\"/g, '"'))
127 .join("");
128
129 /**
130 * TXT values for `fqdn` from one DoH resolver. Any transport or parse
131 * failure reads as "no records yet".
132 */
133 export const resolveTxt = (
134 resolver: string,
135 fqdn: string,
136 ): Effect.Effect<ReadonlyArray<string>, never, HttpClient.HttpClient> =>
137 Effect.gen(function* () {
138 const client = yield* HttpClient.HttpClient;
139 const request = HttpClientRequest.get(resolver).pipe(
140 HttpClientRequest.setUrlParams({ name: fqdn, type: "TXT" }),
141 HttpClientRequest.setHeader("Accept", "application/dns-json"),
142 );
143 const response = yield* client.execute(request);
144 const body = (yield* response.json) as { Answer?: DohAnswer[] };
145 return (body.Answer ?? [])
146 .filter((answer) => answer.type === 16 && typeof answer.data === "string")
147 .map((answer) => unquote(answer.data!));
148 }).pipe(
149 Effect.timeout("3 seconds"),
150 Effect.orElseSucceed(() => [] as ReadonlyArray<string>),
151 );
152
153 /**
154 * Wait `initialDelay`, then poll for the exact challenge value and wait
155 * `delay`. Explicit resolvers must all agree; automatic lookup accepts all
156 * discovered nameservers or a positive default DoH answer. Discovery and
157 * polling share `timeout`; the delays before and after are outside it.
158 */
159 export const waitForTxt = (
160 fqdn: string,
161 value: string,
162 options: PropagationOptions = {},
163 ): Effect.Effect<void, DnsPropagationTimeout, HttpClient.HttpClient> =>
164 Effect.gen(function* () {
165 const interval = options.interval ?? "3 seconds";
166 const timeout = options.timeout ?? "45 seconds";
167 // Bounded by `timeout` below, so poll for the caller's whole budget.
168 const attempts = Math.max(
169 1,
170 Math.ceil(Duration.toMillis(timeout) / Duration.toMillis(interval)),
171 );
172 yield* Effect.sleep(options.initialDelay ?? "0 seconds");
173 const propagated = yield* Effect.gen(function* () {
174 // Explicit resolvers must work even when node:dns is available.
175 const dns = options.resolvers === undefined ? yield* nodeDns : undefined;
176 const servers =
177 dns === undefined
178 ? []
179 : yield* authoritativeServers(dns, fqdn).pipe(
180 Effect.timeout("5 seconds"),
181 Effect.orElseSucceed(() => [] as ReadonlyArray<string>),
182 );
183 const check = Effect.all(
184 {
185 direct: Effect.all(
186 dns === undefined
187 ? []
188 : servers.map((server) =>
189 resolveTxtAt(dns, server, fqdn).pipe(
190 Effect.map((values) => values.includes(value)),
191 ),
192 ),
193 { concurrency: "unbounded" },
194 ),
195 doh: Effect.forEach(
196 options.resolvers ?? DEFAULT_RESOLVERS,
197 (resolver) =>
198 resolveTxt(resolver, fqdn).pipe(Effect.map((values) => values.includes(value))),
199 { concurrency: "unbounded" },
200 ),
201 },
202 { concurrency: "unbounded" },
203 ).pipe(
204 Effect.map(({ direct, doh }) =>
205 options.resolvers !== undefined
206 ? doh.length > 0 && doh.every(Boolean)
207 : (direct.length > 0 && direct.every(Boolean)) || doh.some(Boolean),
208 ),
209 );
210 return yield* check.pipe(
211 Effect.repeat({
212 schedule: Schedule.spaced(interval),
213 until: (seen) => seen,
214 times: attempts,
215 }),
216 );
217 }).pipe(
218 Effect.timeoutOrElse({
219 duration: timeout,
220 orElse: () => Effect.fail(new DnsPropagationTimeout({ fqdn, value })),
221 }),
222 );
223 if (!propagated) {
224 return yield* new DnsPropagationTimeout({ fqdn, value });
225 }
226 yield* propagationDelay(options);
227 });