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

main
ts 331 lines 12.2 KB
Raw
1 import * as web3 from "@distilled.cloud/cloudflare/web3";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Predicate from "effect/Predicate";
7 import * as Stream from "effect/Stream";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10 import { listAllZones } from "../Zone/lookup.ts";
11
12 const TypeId = "Cloudflare.Web3.Hostname" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * The gateway a Web3 hostname resolves through: an Ethereum gateway, an
17 * IPFS gateway pinned to a single DNSLink, or an IPFS universal-path
18 * gateway that can serve any CID under `/ipfs/...` / `/ipns/...`.
19 */
20 export type HostnameTarget = "ethereum" | "ipfs" | "ipfs_universal_path";
21
22 /**
23 * Activation status of a Web3 hostname. Hostnames start `pending` until the
24 * CNAME is verified at the edge; deletion is asynchronous (`deleting`).
25 */
26 export type HostnameStatus = "active" | "pending" | "deleting" | "error";
27
28 export interface HostnameProps {
29 /**
30 * The zone the hostname is created in. The hostname must be a subdomain
31 * of (or equal to) the zone's name.
32 *
33 * Stable — moving a hostname to another zone triggers a replacement.
34 */
35 zoneId: string;
36 /**
37 * The hostname that points to the target gateway via CNAME, e.g.
38 * `gateway.example.com`.
39 *
40 * Immutable — the hostname is the resource's identity and cannot be
41 * renamed, so changing it triggers a replacement.
42 */
43 name: string;
44 /**
45 * The target gateway of the hostname.
46 *
47 * Immutable — the API cannot change a hostname's target after creation,
48 * so changing it triggers a replacement.
49 */
50 target: HostnameTarget;
51 /**
52 * The DNSLink value used when `target` is `ipfs`, e.g.
53 * `/ipns/onboarding.ipfs.cloudflare.com`. Mutable — patched in place.
54 */
55 dnslink?: string;
56 /**
57 * An optional description of the hostname. Mutable — patched in place.
58 */
59 description?: string;
60 }
61
62 export interface HostnameAttributes {
63 /** Cloudflare-assigned identifier of the Web3 hostname. */
64 hostnameId: string;
65 /** The zone the hostname belongs to. */
66 zoneId: string;
67 /** The hostname that points to the target gateway via CNAME. */
68 name: string;
69 /** The target gateway of the hostname. */
70 target: HostnameTarget;
71 /** The DNSLink value, if the target is `ipfs`. */
72 dnslink: string | undefined;
73 /** The hostname's description, if set. */
74 description: string | undefined;
75 /** Activation status of the hostname. */
76 status: HostnameStatus;
77 /** ISO8601 creation timestamp. */
78 createdOn: string | undefined;
79 /** ISO8601 last-modified timestamp. */
80 modifiedOn: string | undefined;
81 }
82
83 export type Hostname = Resource<TypeId, HostnameProps, HostnameAttributes, never, Providers>;
84
85 /**
86 * A Cloudflare Web3 gateway hostname — serve Ethereum or IPFS content from
87 * a hostname on your zone via Cloudflare's distributed web gateways.
88 *
89 * A hostname's identity is its `name` within the zone; only `dnslink` and
90 * `description` are mutable, so changing `name`, `target`, or `zoneId`
91 * triggers a replacement. Hostnames activate asynchronously: they start in
92 * `pending` status and flip to `active` once the CNAME is verified.
93 *
94 * Note: Cloudflare has restricted Web3 gateways for new customers — on
95 * accounts without the entitlement, creation fails with the typed
96 * `Web3HostnameNotEntitled` error.
97 *
98 * Safety: Web3 hostnames carry no ownership markers. When there is no prior
99 * state, `read` scans the zone for an existing hostname with the same name
100 * and reports it as `Unowned`, so the engine refuses to take it over unless
101 * `--adopt` (or `adopt(true)`) is set.
102 * ### IPFS gateway
103 * **Example:** IPFS hostname pinned to a DNSLink
104 * ```typescript
105 * const gateway = yield* Cloudflare.Web3.Hostname("IpfsGateway", {
106 * zoneId: zone.zoneId,
107 * name: "ipfs.example.com",
108 * target: "ipfs",
109 * dnslink: "/ipns/onboarding.ipfs.cloudflare.com",
110 * description: "IPFS gateway for example.com",
111 * });
112 * ```
113 *
114 * **Example:** IPFS universal-path gateway
115 * ```typescript
116 * // Serves any CID under /ipfs/... and /ipns/... paths.
117 * const universal = yield* Cloudflare.Web3.Hostname("UniversalGateway", {
118 * zoneId: zone.zoneId,
119 * name: "gateway.example.com",
120 * target: "ipfs_universal_path",
121 * });
122 * ```
123 *
124 * ### Ethereum gateway
125 * **Example:** Ethereum RPC hostname
126 * ```typescript
127 * yield* Cloudflare.Web3.Hostname("EthGateway", {
128 * zoneId: zone.zoneId,
129 * name: "eth.example.com",
130 * target: "ethereum",
131 * });
132 * ```
133 *
134 * @see https://developers.cloudflare.com/web3/
135 *
136 * @resource
137 * @product Web3
138 * @category Domains & DNS
139 */
140 export const Hostname = Resource<Hostname>(TypeId, {
141 aliases: ["Cloudflare.Web3Hostname"],
142 });
143
144 /**
145 * Returns true if the given value is a Hostname resource.
146 */
147 export const isHostname = (value: unknown): value is Hostname =>
148 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
149
150 export const HostnameProvider = () =>
151 Provider.succeed(Hostname, {
152 stables: ["hostnameId", "zoneId", "name", "target", "createdOn"],
153
154 // Web3 hostnames live inside a zone (`/zones/{id}/web3/hostnames`) with no
155 // account-wide enumeration API, so fan out over every zone via
156 // `listAllZones` and exhaustively paginate the per-zone list. Zones without
157 // the Web3 entitlement (or where the scoped token lacks access) answer
158 // `Forbidden` — skip them rather than failing the whole enumeration.
159 list: Effect.fn(function* () {
160 const { accountId } = yield* yield* CloudflareEnvironment;
161 const zones = yield* listAllZones(accountId);
162 const rows = yield* Effect.forEach(
163 zones,
164 (zone) =>
165 web3.listHostnames.pages({ zoneId: zone.id }).pipe(
166 Stream.runCollect,
167 Effect.map((chunk) =>
168 Array.from(chunk).flatMap((page) =>
169 (page.result ?? [])
170 .filter((raw) => raw.status !== "deleting")
171 .map((raw): HostnameAttributes => toAttributes(raw, zone.id)),
172 ),
173 ),
174 Effect.catchTag("Forbidden", () => Effect.succeed([])),
175 ),
176 { concurrency: 10 },
177 );
178 return rows.flat();
179 }),
180
181 diff: Effect.fn(function* ({ olds = {}, news, output }) {
182 const o = olds as Partial<HostnameProps>;
183 const n = news as HostnameProps;
184 const oldName = output?.name ?? o.name;
185 const oldTarget = output?.target ?? o.target;
186 if (oldName === undefined && oldTarget === undefined) return undefined;
187 // The hostname is the resource's identity — no rename API exists.
188 if (oldName !== undefined && oldName !== n.name) {
189 return { action: "replace" } as const;
190 }
191 // The target gateway is immutable after creation.
192 if (oldTarget !== undefined && oldTarget !== n.target) {
193 return { action: "replace" } as const;
194 }
195 // zoneId is Input<string>; compare only once both are concrete.
196 const oldZone = output?.zoneId ?? o.zoneId;
197 if (typeof oldZone === "string" && typeof n.zoneId === "string" && oldZone !== n.zoneId) {
198 return { action: "replace" } as const;
199 }
200 return undefined;
201 }),
202
203 read: Effect.fn(function* ({ output, olds }) {
204 const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
205 if (zoneId === undefined) return undefined;
206
207 // Owned path: refresh by our persisted hostname id.
208 if (output?.hostnameId) {
209 const observed = yield* getHostname(zoneId, output.hostnameId);
210 if (observed) return toAttributes(observed, zoneId);
211 }
212
213 // Cold lookup: a hostname with this name may already exist in the
214 // zone. Web3 hostnames carry no ownership markers, so we cannot
215 // prove we created it — brand it `Unowned` so the engine refuses
216 // to take over unless `adopt` is set.
217 const name = output?.name ?? olds?.name;
218 if (name !== undefined) {
219 const observed = yield* findByName(zoneId, name);
220 if (observed) return Unowned(toAttributes(observed, zoneId));
221 }
222 return undefined;
223 }),
224
225 reconcile: Effect.fn(function* ({ news, output }) {
226 // Inputs have been resolved to concrete strings by Plan.
227 const zoneId = news.zoneId as string;
228
229 // 1. Observe — the hostname id cached on `output` is a hint, not a
230 // guarantee: a missing hostname falls through to the name scan
231 // and then to create.
232 let observed = output?.hostnameId ? yield* getHostname(zoneId, output.hostnameId) : undefined;
233
234 // 2. Fall back to scanning the zone for a name match. Ownership has
235 // already been verified upstream — `read` reports existing
236 // hostnames as `Unowned` and the engine gates takeover behind
237 // the adopt policy before reconcile ever runs.
238 if (!observed) {
239 observed = yield* findByName(zoneId, news.name);
240 }
241
242 // 3. Ensure — create when missing. Hostnames activate
243 // asynchronously; return the `pending` state as-is rather than
244 // polling for `active` (activation depends on CNAME/edge
245 // propagation outside our control).
246 if (!observed) {
247 const created = yield* web3.createHostname({
248 zoneId,
249 name: news.name,
250 target: news.target,
251 dnslink: news.dnslink,
252 description: news.description,
253 });
254 return toAttributes(created, zoneId);
255 }
256
257 // 4. Sync — diff observed dnslink/description against desired;
258 // skip the patch call entirely on a no-op.
259 const dirty =
260 (news.dnslink !== undefined && (observed.dnslink ?? undefined) !== news.dnslink) ||
261 (news.description !== undefined &&
262 (observed.description ?? undefined) !== news.description);
263 if (dirty) {
264 observed = yield* web3.patchHostname({
265 zoneId,
266 identifier: observed.id ?? "",
267 dnslink: news.dnslink,
268 description: news.description,
269 });
270 }
271
272 return toAttributes(observed, zoneId);
273 }),
274
275 delete: Effect.fn(function* ({ output }) {
276 // Deletion is asynchronous (the hostname lingers in `deleting`
277 // status); a hostname that is already gone answers 404 with the
278 // typed Web3HostnameNotFound tag — treat it as done.
279 yield* web3
280 .deleteHostname({
281 zoneId: output.zoneId,
282 identifier: output.hostnameId,
283 })
284 .pipe(Effect.catchTag("Web3HostnameNotFound", () => Effect.void));
285 }),
286 });
287
288 type ObservedHostname = web3.GetHostnameResponse;
289
290 /**
291 * Read a hostname by id, mapping "gone" (`Web3HostnameNotFound`, Cloudflare
292 * error code 1002 "Hostname does not exist.") to `undefined`. A hostname in
293 * `deleting` status is treated as already gone — it cannot be converged.
294 */
295 const getHostname = (zoneId: string, hostnameId: string) =>
296 web3.getHostname({ zoneId, identifier: hostnameId }).pipe(
297 Effect.map((hostname): ObservedHostname | undefined =>
298 hostname.status === "deleting" ? undefined : hostname,
299 ),
300 Effect.catchTag("Web3HostnameNotFound", () => Effect.undefined),
301 );
302
303 /**
304 * Find a hostname by exact name within the zone. The name is a hostname's
305 * identity — Cloudflare rejects duplicates — so at most one (non-deleting)
306 * hostname can match.
307 */
308 const findByName = (zoneId: string, name: string) =>
309 web3.listHostnames.items({ zoneId }).pipe(
310 Stream.runCollect,
311 Effect.map((chunk) =>
312 Array.from(chunk).find(
313 (hostname): hostname is ObservedHostname =>
314 hostname.name === name && hostname.status !== "deleting",
315 ),
316 ),
317 );
318
319 const toAttributes = (hostname: ObservedHostname, zoneId: string): HostnameAttributes => ({
320 // Cloudflare always echoes id/name/target/status for a persisted
321 // hostname — distilled just types every response field as optional.
322 hostnameId: hostname.id ?? "",
323 zoneId,
324 name: hostname.name ?? "",
325 target: (hostname.target ?? "ipfs") as HostnameTarget,
326 dnslink: hostname.dnslink ?? undefined,
327 description: hostname.description ?? undefined,
328 status: (hostname.status ?? "pending") as HostnameStatus,
329 createdOn: hostname.createdOn ?? undefined,
330 modifiedOn: hostname.modifiedOn ?? undefined,
331 });