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

main
ts 316 lines 10.7 KB
Raw
1 import * as web3 from "@distilled.cloud/cloudflare/web3";
2 import * as Provider from "alchemy/Provider";
3 import { Resource } from "alchemy/Resource";
4 import * as Effect from "effect/Effect";
5 import * as Predicate from "effect/Predicate";
6 import * as Stream from "effect/Stream";
7 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
8 import type { Providers } from "../Providers.ts";
9 import { listAllZones } from "../Zone/lookup.ts";
10
11 const TypeId = "Cloudflare.Web3.HostnameContentList" as const;
12 type TypeId = typeof TypeId;
13
14 /**
15 * The kind of content a content-list entry blocks: a CID (`cid`) or a
16 * content path (`content_path`).
17 */
18 export type ContentListEntryType = "cid" | "content_path";
19
20 /**
21 * A single entry of an IPFS universal-path content list.
22 */
23 export interface ContentListEntry {
24 /**
25 * The CID or content path of content to block, e.g.
26 * `QmXoypizjW3WknFiJnKLwHCnL72vedxjQkDDP1mXWo6uco` (`cid`) or
27 * `/ipfs/QmXoypizjW3WknFiJnKLwHCnL72vedxjQkDDP1mXWo6uco/wiki` (`content_path`).
28 */
29 content: string;
30 /**
31 * The type of content list entry to block.
32 */
33 type: ContentListEntryType;
34 /**
35 * An optional description of the content list entry.
36 */
37 description?: string;
38 }
39
40 export interface HostnameContentListProps {
41 /**
42 * The zone the hostname belongs to.
43 *
44 * Stable — moving to another zone triggers a replacement.
45 */
46 zoneId: string;
47 /**
48 * The Web3 hostname the content list belongs to. Must be an
49 * `ipfs_universal_path` hostname — other targets reject content-list
50 * operations.
51 *
52 * Stable — pointing at another hostname triggers a replacement.
53 */
54 hostnameId: string;
55 /**
56 * Behavior of the content list. Cloudflare currently only supports
57 * `block`.
58 * @default "block"
59 */
60 action?: "block";
61 /**
62 * The full desired set of content list entries. The list is replaced
63 * declaratively on every change (bulk PUT) — entries not present here
64 * are removed.
65 * @default []
66 */
67 entries?: ContentListEntry[];
68 }
69
70 export interface HostnameContentListAttributes {
71 /** The zone the hostname belongs to. */
72 zoneId: string;
73 /** The Web3 hostname the content list belongs to. */
74 hostnameId: string;
75 /** Behavior of the content list. */
76 action: "block";
77 /** The current content list entries. */
78 entries: ContentListEntry[];
79 }
80
81 export type HostnameContentList = Resource<
82 TypeId,
83 HostnameContentListProps,
84 HostnameContentListAttributes,
85 never,
86 Providers
87 >;
88
89 /**
90 * The IPFS content-blocking list of a Web3 universal-path gateway hostname —
91 * blocks specific CIDs or content paths from being served.
92 *
93 * The content list is a per-hostname singleton: it always exists for an
94 * `ipfs_universal_path` hostname (empty by default), so this resource never
95 * creates or deletes a physical object. Reconciliation replaces the whole
96 * list declaratively via the bulk PUT, and destroy resets the list to empty.
97 * ### Blocking content
98 * **Example:** Block a CID and a content path
99 * ```typescript
100 * const gateway = yield* Cloudflare.Web3.Hostname("UniversalGateway", {
101 * zoneId: zone.zoneId,
102 * name: "gateway.example.com",
103 * target: "ipfs_universal_path",
104 * });
105 *
106 * yield* Cloudflare.Web3.HostnameContentList("Blocklist", {
107 * zoneId: zone.zoneId,
108 * hostnameId: gateway.hostnameId,
109 * entries: [
110 * {
111 * type: "cid",
112 * content: "QmXoypizjW3WknFiJnKLwHCnL72vedxjQkDDP1mXWo6uco",
113 * description: "blocked CID",
114 * },
115 * {
116 * type: "content_path",
117 * content: "/ipfs/QmXoypizjW3WknFiJnKLwHCnL72vedxjQkDDP1mXWo6uco/wiki",
118 * },
119 * ],
120 * });
121 * ```
122 *
123 * **Example:** Clear the blocklist
124 * ```typescript
125 * // An empty entries array removes every block (also what destroy does).
126 * yield* Cloudflare.Web3.HostnameContentList("Blocklist", {
127 * zoneId: zone.zoneId,
128 * hostnameId: gateway.hostnameId,
129 * entries: [],
130 * });
131 * ```
132 *
133 * @see https://developers.cloudflare.com/web3/
134 *
135 * @resource
136 * @product Web3
137 * @category Domains & DNS
138 */
139 export const HostnameContentList = Resource<HostnameContentList>(TypeId, {
140 aliases: ["Cloudflare.Web3HostnameContentList"],
141 });
142
143 /**
144 * Returns true if the given value is a HostnameContentList resource.
145 */
146 export const isHostnameContentList = (value: unknown): value is HostnameContentList =>
147 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
148
149 export const HostnameContentListProvider = () =>
150 Provider.succeed(HostnameContentList, {
151 stables: ["zoneId", "hostnameId"],
152
153 list: Effect.fn(function* () {
154 const { accountId } = yield* yield* CloudflareEnvironment;
155 // The content list is a per-hostname singleton keyed by
156 // {zoneId, hostnameId}. Enumerate every zone, list its Web3
157 // hostnames, keep only universal-path gateways (other targets
158 // reject content-list ops), and read each one's list.
159 const zones = yield* listAllZones(accountId);
160 const rows = yield* Effect.forEach(
161 zones,
162 (zone) =>
163 web3.listHostnames.items({ zoneId: zone.id }).pipe(
164 Stream.runCollect,
165 Effect.map((chunk) =>
166 Array.from(chunk).filter(
167 (h): h is typeof h & { id: string } =>
168 h.id != null && h.target === "ipfs_universal_path",
169 ),
170 ),
171 Effect.flatMap((hostnames) =>
172 Effect.forEach(
173 hostnames,
174 (h) =>
175 observeContentList(zone.id, h.id).pipe(
176 Effect.catchTag("Forbidden", () => Effect.undefined),
177 ),
178 { concurrency: 10 },
179 ),
180 ),
181 // Web3 is entitlement-gated and freshly minted tokens can
182 // briefly 403 — skip zones we can't enumerate.
183 Effect.catchTag("Forbidden", () => Effect.succeed([])),
184 ),
185 { concurrency: 10 },
186 );
187 return rows.flat().filter((row): row is HostnameContentListAttributes => row !== undefined);
188 }),
189
190 diff: Effect.fn(function* ({ olds = {}, news, output }) {
191 const o = olds as Partial<HostnameContentListProps>;
192 const n = news as HostnameContentListProps;
193 // zoneId/hostnameId are Input<string>; compare only once both
194 // sides are concrete. The content list is a sub-singleton of the
195 // hostname — pointing elsewhere replaces it.
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 const oldHostname = output?.hostnameId ?? o.hostnameId;
201 if (
202 typeof oldHostname === "string" &&
203 typeof n.hostnameId === "string" &&
204 oldHostname !== n.hostnameId
205 ) {
206 return { action: "replace" } as const;
207 }
208 return undefined;
209 }),
210
211 read: Effect.fn(function* ({ output, olds }) {
212 const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
213 const hostnameId =
214 output?.hostnameId ?? (typeof olds?.hostnameId === "string" ? olds.hostnameId : undefined);
215 if (zoneId === undefined || hostnameId === undefined) return undefined;
216 // Settings-singleton semantics: the list always exists for a
217 // universal-path hostname (empty by default), so it is never
218 // `Unowned`. A deleted hostname reads as gone.
219 return yield* observeContentList(zoneId, hostnameId);
220 }),
221
222 reconcile: Effect.fn(function* ({ news }) {
223 // Inputs have been resolved to concrete strings by Plan.
224 const zoneId = news.zoneId as string;
225 const hostnameId = news.hostnameId as string;
226 const desired: HostnameContentListAttributes = {
227 zoneId,
228 hostnameId,
229 action: news.action ?? "block",
230 entries: news.entries ?? [],
231 };
232
233 // Observe — read the live list; the singleton always exists for a
234 // universal-path hostname, so "missing" only means the hostname
235 // itself is gone (which is a real failure for reconcile).
236 const observed = yield* observeContentList(zoneId, hostnameId);
237
238 // Sync — the bulk PUT replaces action + entries declaratively;
239 // skip the API call entirely on a no-op.
240 if (observed && sameContentList(observed, desired)) {
241 return observed;
242 }
243 yield* web3.putHostnameIpfsUniversalPathContentList({
244 zoneId,
245 identifier: hostnameId,
246 action: desired.action,
247 entries: desired.entries,
248 });
249 return desired;
250 }),
251
252 delete: Effect.fn(function* ({ output }) {
253 // There is no DELETE endpoint — destroying the resource resets the
254 // singleton to its empty default. If the hostname itself is already
255 // gone (or no longer a universal-path gateway), there is nothing
256 // left to reset.
257 yield* web3
258 .putHostnameIpfsUniversalPathContentList({
259 zoneId: output.zoneId,
260 identifier: output.hostnameId,
261 action: "block",
262 entries: [],
263 })
264 .pipe(
265 Effect.catchTag(["Web3HostnameNotFound", "InvalidWeb3HostnameTarget"], () => Effect.void),
266 );
267 }),
268 });
269
270 /**
271 * Read the content list (action) plus its entries, mapping a gone hostname
272 * (`Web3HostnameNotFound`, code 1002) or a hostname that is not a
273 * universal-path gateway (`InvalidWeb3HostnameTarget`, code 1006) to
274 * `undefined`.
275 */
276 const observeContentList = (zoneId: string, hostnameId: string) =>
277 Effect.gen(function* () {
278 const list = yield* web3.getHostnameIpfsUniversalPathContentList({
279 zoneId,
280 identifier: hostnameId,
281 });
282 const entries = yield* web3.listHostnameIpfsUniversalPathContentListEntries({
283 zoneId,
284 identifier: hostnameId,
285 });
286 return {
287 zoneId,
288 hostnameId,
289 action: (list.action ?? "block") as "block",
290 entries: (entries.entries ?? []).map((entry): ContentListEntry => ({
291 content: entry.content ?? "",
292 type: (entry.type ?? "cid") as ContentListEntryType,
293 ...(entry.description != null ? { description: entry.description } : {}),
294 })),
295 } satisfies HostnameContentListAttributes;
296 }).pipe(
297 Effect.catchTag(["Web3HostnameNotFound", "InvalidWeb3HostnameTarget"], () => Effect.undefined),
298 );
299
300 /**
301 * Order-insensitive comparison of two content lists by (content, type,
302 * description).
303 */
304 const sameContentList = (
305 observed: HostnameContentListAttributes,
306 desired: HostnameContentListAttributes,
307 ) =>
308 observed.action === desired.action &&
309 observed.entries.length === desired.entries.length &&
310 serializeEntries(observed.entries) === serializeEntries(desired.entries);
311
312 const serializeEntries = (entries: ContentListEntry[]) =>
313 entries
314 .map((entry) => `${entry.type}${entry.content}${entry.description ?? ""}`)
315 .sort()
316 .join("");