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

main
ts 148 lines 5.58 KB
Raw
1 // Leaf modules, not the root, so a Worker using `zoneSolver` doesn't bundle
2 // the ACME providers.
3 import { propagationDelay, waitForTxt } from "@alchemy.run/acme/Dns";
4 import {
5 dnsSolverLayer,
6 type DnsChallengeRecord,
7 type DnsSolver,
8 type DnsSolverDescriptor,
9 } from "@alchemy.run/acme/DnsSolver";
10 import { DnsSolverError } from "@alchemy.run/acme/Errors";
11 import type { Credentials } from "@distilled.cloud/cloudflare/Credentials";
12 import * as dns from "@distilled.cloud/cloudflare/dns";
13 import type { Input } from "alchemy/Input";
14 import type { RuntimeContext } from "alchemy/RuntimeContext";
15 import * as Effect from "effect/Effect";
16 import type * as HttpClient from "effect/http/HttpClient";
17 import * as Stream from "effect/Stream";
18 import type { WriteDnsClient } from "./DNS/WriteDns.ts";
19
20 /** Solver descriptor: publish `_acme-challenge` TXT records in a Cloudflare zone. */
21 export interface CloudflareDnsSolver extends DnsSolverDescriptor {
22 readonly type: "Cloudflare.DNS";
23 readonly zoneId: string;
24 }
25
26 /**
27 * DNS-01 through a Cloudflare zone's records, for `ACME.Certificate`.
28 * `Cloudflare.providers()` registers its implementation.
29 *
30 * **Example:**
31 * ```typescript
32 * const account = yield* LetsEncrypt;
33 * const zone = yield* Zone;
34 * const wildcard = yield* ACME.Certificate("Wildcard", {
35 * account,
36 * identifiers: ["*.example.com"],
37 * solver: Cloudflare.ACME.ZoneSolver(zone),
38 * });
39 * ```
40 */
41 export const ZoneSolver = <ZoneId extends Input<string>>(zone: { readonly zoneId: ZoneId }) => ({
42 type: "Cloudflare.DNS" as const,
43 zoneId: zone.zoneId,
44 });
45
46 const CHALLENGE_TTL = 60;
47 /** Post-publish wait for the in-Worker solver. */
48 const RUNTIME_PROPAGATION_DELAY = "60 seconds";
49
50 const unquote = (content: string | null | undefined): string =>
51 (content ?? "").replace(/^"|"$/g, "");
52
53 const solverError = (message: string) => (cause: unknown) => new DnsSolverError({ message, cause });
54
55 /** Deploy-time solver over the distilled DNS SDK (zone id fixed). */
56 export const makeZoneSolver = (zoneId: string): DnsSolver<Credentials | HttpClient.HttpClient> => {
57 const matching = (record: DnsChallengeRecord) =>
58 dns.listRecords.items({ zoneId, name: { exact: record.fqdn }, type: "TXT" }).pipe(
59 Stream.filter((r) => r.name === record.fqdn && unquote(r.content) === record.value),
60 Stream.runCollect,
61 Effect.map((chunk) => Array.from(chunk)),
62 );
63 return {
64 present: (record) =>
65 Effect.gen(function* () {
66 const existing = yield* matching(record);
67 if (existing.length > 0) return;
68 yield* dns.createRecord({
69 zoneId,
70 type: "TXT",
71 name: record.fqdn,
72 content: record.value,
73 ttl: CHALLENGE_TTL,
74 });
75 }).pipe(Effect.mapError(solverError(`Could not publish TXT ${record.fqdn}`))),
76 cleanup: (record) =>
77 Effect.gen(function* () {
78 const existing = yield* matching(record);
79 yield* Effect.forEach(existing, (r) => dns.deleteRecord({ zoneId, dnsRecordId: r.id }));
80 }).pipe(Effect.mapError(solverError(`Could not remove TXT ${record.fqdn}`))),
81 // Let Cloudflare publish before any intercepted/recursive lookup can cache
82 // a negative answer for the zone's SOA minimum (often 30 minutes).
83 propagated: (record, options) =>
84 waitForTxt(record.fqdn, record.value, {
85 ...options,
86 initialDelay: options.initialDelay ?? "60 seconds",
87 timeout: options.timeout ?? "90 seconds",
88 }),
89 };
90 };
91
92 /**
93 * Registers the `Cloudflare.DNS` solver type with the ACME provider, over the
94 * Cloudflare credentials in context. `Cloudflare.providers()` includes it.
95 */
96 export const ZoneSolverLive = dnsSolverLayer("Cloudflare.DNS", (descriptor) =>
97 typeof descriptor.zoneId === "string" && descriptor.zoneId.length > 0
98 ? Effect.succeed(makeZoneSolver(descriptor.zoneId))
99 : Effect.fail(new DnsSolverError({ message: "Cloudflare DNS solver requires a zoneId." })),
100 );
101
102 /**
103 * Runtime solver over a bound {@link WriteDnsClient}, for
104 * `ACME.IssueCertificate` inside a Worker or Service.
105 *
106 * **Example:**
107 * ```typescript
108 * const dns = yield* Cloudflare.DNS.WriteDns(Zone);
109 * const issued = yield* acme.issue({
110 * identifiers: ["*.tenant.example.com"],
111 * solver: Cloudflare.ACME.zoneSolver(dns),
112 * });
113 * ```
114 */
115 export const zoneSolver = (client: WriteDnsClient): DnsSolver<RuntimeContext> => {
116 const published = new Map<string, string>();
117 const keyOf = (record: DnsChallengeRecord) => `${record.fqdn}|${record.value}`;
118 return {
119 present: (record) =>
120 client
121 .createDnsRecord({
122 type: "TXT",
123 name: record.fqdn,
124 content: record.value,
125 ttl: CHALLENGE_TTL,
126 })
127 .pipe(
128 Effect.tap((created) => Effect.sync(() => published.set(keyOf(record), created.id))),
129 Effect.asVoid,
130 Effect.mapError(solverError(`Could not publish TXT ${record.fqdn}`)),
131 ),
132 cleanup: (record) =>
133 Effect.suspend(() => {
134 const id = published.get(keyOf(record));
135 if (id === undefined) return Effect.void;
136 return client.deleteDnsRecord(id).pipe(
137 Effect.tap(() => Effect.sync(() => published.delete(keyOf(record)))),
138 Effect.asVoid,
139 Effect.mapError(solverError(`Could not remove TXT ${record.fqdn}`)),
140 );
141 }),
142 // Inside a Worker there is no authoritative lookup and public DoH
143 // resolvers cache stale sets; Cloudflare's edge serves a new record
144 // within seconds, so a fixed wait is the reliable choice here.
145 propagated: (_record, options) =>
146 propagationDelay({ delay: options.delay ?? RUNTIME_PROPAGATION_DELAY }),
147 };
148 };