@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 430 lines 16 KB
Raw
1 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { arrayEqualsUnordered } from "alchemy/Util/equal";
7 import * as Effect from "effect/Effect";
8 import * as Predicate from "effect/Predicate";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
12 import type { Providers } from "../Providers.ts";
13
14 const TypeId = "Cloudflare.Gateway.Location" as const;
15 type TypeId = typeof TypeId;
16
17 /**
18 * A source network range (CIDR) requests at a Gateway location may
19 * originate from.
20 */
21 export interface LocationNetwork {
22 /**
23 * IPv4 CIDR, e.g. `203.0.113.0/24`.
24 */
25 network: string;
26 }
27
28 /**
29 * Destination endpoint configuration for a Gateway location. Re-exports
30 * distilled's request shape so every server-recognised knob (DoH networks
31 * and token requirement, DoT, IPv4/IPv6 toggles) is available without
32 * re-declaring the structure.
33 */
34 export type LocationEndpoints = NonNullable<zeroTrust.UpdateGatewayLocationRequest["endpoints"]>;
35
36 export interface LocationProps {
37 /**
38 * Display name for the location. Used as a stable identifier so the
39 * provider can locate it by name during adoption / state recovery. If
40 * omitted, a unique name is generated from the app, stage, and logical ID.
41 *
42 * @default ${app}-${stage}-${id}
43 */
44 name?: string;
45 /**
46 * Whether this location is the default for the account. Cloudflare
47 * rejects demoting the current default directly — promote another
48 * location instead. Mutable.
49 *
50 * @default false
51 */
52 clientDefault?: boolean;
53 /**
54 * Whether the location must resolve EDNS (EDNS Client Subnet) queries.
55 * Mutable.
56 *
57 * @default false
58 */
59 ecsSupport?: boolean;
60 /**
61 * Identifier of the pair of DNS destination IPv4 addresses assigned to
62 * this location. When absent, Cloudflare's shared IPv4 pair is used.
63 * Mutable.
64 */
65 dnsDestinationIpsId?: string;
66 /**
67 * Destination endpoint configuration (DoH / DoT / IPv4 / IPv6 toggles
68 * and source networks). Mutable.
69 */
70 endpoints?: LocationEndpoints;
71 /**
72 * Source network ranges (IPv4 CIDRs) requests at this location originate
73 * from. Only takes effect when non-empty and the IPv4 endpoint is
74 * enabled. Mutable.
75 *
76 * @default []
77 */
78 networks?: LocationNetwork[];
79 }
80
81 export interface LocationAttributes {
82 /** UUID of the location, assigned by Cloudflare. */
83 locationId: string;
84 /** Cloudflare account that owns the location. */
85 accountId: string;
86 /** Display name of the location. */
87 name: string;
88 /** Whether this location is the account default. */
89 clientDefault: boolean;
90 /** Whether the location resolves EDNS queries. */
91 ecsSupport: boolean;
92 /**
93 * Server-generated DNS-over-HTTPS subdomain that receives this
94 * location's DNS requests (`https://<dohSubdomain>.cloudflare-gateway.com/dns-query`).
95 */
96 dohSubdomain: string | undefined;
97 /** Auto-generated IPv6 destination IP assigned to this location. */
98 ip: string | undefined;
99 /** Primary DNS destination IPv4 address (read-only, server-assigned). */
100 ipv4Destination: string | undefined;
101 /** Identifier of the DNS destination IPv4 pair, if a dedicated pair is assigned. */
102 dnsDestinationIpsId: string | undefined;
103 /** Source network ranges configured for this location. */
104 networks: LocationNetwork[];
105 /** ISO8601 creation timestamp. */
106 createdAt: string | undefined;
107 /** ISO8601 last-update timestamp. */
108 updatedAt: string | undefined;
109 }
110
111 export type Location = Resource<TypeId, LocationProps, LocationAttributes, never, Providers>;
112
113 /**
114 * A Cloudflare Zero Trust Gateway DNS location — a configured source of
115 * DNS traffic (an office, a home network, a device fleet) with its own
116 * DNS-over-HTTPS endpoint and optional dedicated destination IPs.
117 *
118 * Cloudflare assigns each location a stable `dohSubdomain`; point your
119 * network's DoH resolver at
120 * `https://<dohSubdomain>.cloudflare-gateway.com/dns-query` and Gateway
121 * DNS policies apply to its traffic. All declared properties converge in
122 * place — nothing on a location forces a replacement.
123 * ### Creating a Location
124 * **Example:** DoH-only location
125 * ```typescript
126 * const office = yield* Cloudflare.Gateway.Location("Office", {
127 * ecsSupport: false,
128 * });
129 * // Point your resolver at the assigned DoH endpoint:
130 * const doh = office.dohSubdomain;
131 * ```
132 *
133 * **Example:** Location with IPv4 source networks
134 * ```typescript
135 * const office = yield* Cloudflare.Gateway.Location("Office", {
136 * networks: [{ network: "203.0.113.0/24" }],
137 * endpoints: {
138 * doh: { enabled: true },
139 * dot: { enabled: false },
140 * ipv4: { enabled: true },
141 * ipv6: { enabled: false },
142 * },
143 * });
144 * ```
145 *
146 * @see https://developers.cloudflare.com/cloudflare-one/connections/connect-devices/agentless/dns/locations/
147 *
148 * @resource
149 * @product Gateway
150 * @category Cloudflare One (Zero Trust)
151 */
152 export const Location = Resource<Location>(TypeId);
153
154 /**
155 * Returns true if the given value is a Location resource.
156 */
157 export const isLocation = (value: unknown): value is Location =>
158 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
159
160 /**
161 * Right after a location create/update, Cloudflare's edge intermittently
162 * answers the write with a 401 `Unauthorized` carrying "This account does
163 * not have access to this feature." even though the account is fully
164 * entitled — the same transient edge/token-propagation blip the read path
165 * rides out as a 403 `Forbidden`. It clears within a few hundred ms, so we
166 * retry the mutation while we see exactly that message. A genuine
167 * entitlement loss carries the same tag, but the bounded retry surfaces it
168 * quickly instead of looping. Matching the message keeps real auth failures
169 * (a bad/expired token) non-retryable.
170 */
171 const isTransientFeatureAccessBlip = (e: {
172 readonly _tag: string;
173 readonly message?: string;
174 }): boolean =>
175 e._tag === "Unauthorized" && (e.message ?? "").includes("does not have access to this feature");
176
177 export const LocationProvider = () =>
178 Provider.succeed(Location, {
179 stables: ["locationId", "accountId", "dohSubdomain", "ip", "createdAt"],
180
181 // Account-scoped collection: enumerate every Gateway location in the
182 // ambient account, exhaustively paginating, and hydrate each into the
183 // exact `read` Attributes shape. The list response already carries the
184 // full per-location state, so no follow-up get is needed.
185 list: Effect.fn(function* () {
186 const { accountId } = yield* yield* CloudflareEnvironment;
187 return yield* zeroTrust.listGatewayLocations.pages({ accountId }).pipe(
188 Stream.runCollect,
189 Effect.map((chunk) =>
190 Array.from(chunk).flatMap((page) =>
191 (page.result ?? [])
192 .map((l) => toAttributes(l, accountId))
193 // The account's default location can't be deleted while it is
194 // the client default (`CannotDeleteDefaultGatewayLocation`);
195 // never enumerate it for account-wide teardown.
196 .filter((l) => !l.clientDefault),
197 ),
198 ),
199 );
200 }),
201
202 diff: Effect.fn(function* ({ output }) {
203 const { accountId } = yield* yield* CloudflareEnvironment;
204 if ((output?.accountId ?? accountId) !== accountId) {
205 return { action: "replace" } as const;
206 }
207 // Everything declared on a location converges via PUT.
208 return undefined;
209 }),
210
211 read: Effect.fn(function* ({ id, output, olds }) {
212 const { accountId } = yield* yield* CloudflareEnvironment;
213 const acct = output?.accountId ?? accountId;
214
215 // Owned path — refresh by the cached location id.
216 if (output?.locationId) {
217 const observed = yield* getLocation(acct, output.locationId);
218 if (observed) return toAttributes(observed, acct);
219 }
220
221 // Cold read — locate by deterministic name. Locations carry no
222 // ownership markers, so report the match as Unowned to gate adoption.
223 const name = yield* resolveName(id, olds?.name ?? output?.name);
224 const match = yield* findByName(acct, name);
225 if (match) return Unowned(toAttributes(match, acct));
226 return undefined;
227 }),
228
229 reconcile: Effect.fn(function* ({ id, news, output }) {
230 const { accountId } = yield* yield* CloudflareEnvironment;
231 const name = yield* resolveName(id, news.name);
232
233 // 1. Observe — the cached id is a hint; fall back to a name scan so
234 // out-of-band deletes / lost state converge.
235 let observed = output?.locationId
236 ? yield* getLocation(accountId, output.locationId)
237 : undefined;
238 if (!observed) {
239 observed = yield* findByName(accountId, name);
240 }
241
242 // 2. Ensure — create with the full desired body when missing. Names
243 // are not unique on Cloudflare's side, so there is no
244 // AlreadyExists race to tolerate.
245 if (!observed) {
246 const created = yield* zeroTrust
247 .createGatewayLocation({
248 accountId,
249 name,
250 clientDefault: news.clientDefault,
251 ecsSupport: news.ecsSupport,
252 dnsDestinationIpsId: news.dnsDestinationIpsId,
253 endpoints: news.endpoints,
254 networks: news.networks,
255 })
256 // See `isTransientFeatureAccessBlip` — ride out the transient
257 // 401 "does not have access to this feature" edge blip.
258 .pipe(
259 Effect.retry({
260 while: isTransientFeatureAccessBlip,
261 // Capped so the bounded retry stays under ~25s in total.
262 schedule: Schedule.min([
263 Schedule.exponential("500 millis"),
264 Schedule.spaced("4 seconds"),
265 ]),
266 times: 8,
267 }),
268 );
269 return toAttributes(created, accountId);
270 }
271
272 // 3. Sync — diff observed cloud state against desired; the update
273 // API is a PUT of the full mutable state, so send everything but
274 // skip the call entirely on a no-op. Networks compare as an
275 // unordered set; endpoints stringify-compare only when declared.
276 const desired = {
277 name,
278 clientDefault: news.clientDefault ?? observed.clientDefault ?? false,
279 ecsSupport: news.ecsSupport ?? observed.ecsSupport ?? false,
280 dnsDestinationIpsId: news.dnsDestinationIpsId,
281 endpoints: news.endpoints,
282 networks: news.networks,
283 };
284 const dirty =
285 observed.name !== desired.name ||
286 (observed.clientDefault ?? false) !== desired.clientDefault ||
287 (observed.ecsSupport ?? false) !== desired.ecsSupport ||
288 (news.dnsDestinationIpsId !== undefined &&
289 observed.dnsDestinationIpsId !== news.dnsDestinationIpsId) ||
290 (news.networks !== undefined && !sameNetworks(observed.networks ?? [], news.networks)) ||
291 (news.endpoints !== undefined && !sameEndpoints(observed.endpoints, news.endpoints));
292 if (dirty) {
293 const updated = yield* zeroTrust
294 .updateGatewayLocation({
295 accountId,
296 locationId: observed.id!,
297 name: desired.name,
298 clientDefault: desired.clientDefault,
299 ecsSupport: desired.ecsSupport,
300 dnsDestinationIpsId: desired.dnsDestinationIpsId,
301 endpoints: desired.endpoints,
302 networks: desired.networks,
303 })
304 // See `isTransientFeatureAccessBlip` — ride out the transient
305 // 401 "does not have access to this feature" edge blip.
306 .pipe(
307 Effect.retry({
308 while: isTransientFeatureAccessBlip,
309 // Capped so the bounded retry stays under ~25s in total.
310 schedule: Schedule.min([
311 Schedule.exponential("500 millis"),
312 Schedule.spaced("4 seconds"),
313 ]),
314 times: 8,
315 }),
316 );
317 return toAttributes(updated, accountId);
318 }
319
320 return toAttributes(observed, accountId);
321 }),
322
323 delete: Effect.fn(function* ({ output }) {
324 // Deleting the default location while it is the client default is a
325 // non-retryable 4xx (CannotDeleteDefaultGatewayLocation, code 1217)
326 // and propagates. A missing location (GatewayLocationNotFound, code
327 // 1103) means we're done.
328 yield* zeroTrust
329 .deleteGatewayLocation({
330 accountId: output.accountId,
331 locationId: output.locationId,
332 })
333 .pipe(Effect.catchTag("GatewayLocationNotFound", () => Effect.void));
334 }),
335 });
336
337 type ObservedLocation = zeroTrust.GetGatewayLocationResponse;
338
339 /**
340 * Read a location by id, mapping "gone" (`GatewayLocationNotFound`,
341 * Cloudflare error code 1103) to `undefined`.
342 */
343 const getLocation = (accountId: string, locationId: string) =>
344 zeroTrust.getGatewayLocation({ accountId, locationId }).pipe(
345 Effect.map((l): ObservedLocation | undefined => l),
346 Effect.catchTag("GatewayLocationNotFound", () => Effect.undefined),
347 );
348
349 /**
350 * Find a location by exact name. Names are not unique on Cloudflare's
351 * side; pick the oldest match for determinism.
352 */
353 const findByName = (accountId: string, name: string) =>
354 zeroTrust.listGatewayLocations.items({ accountId }).pipe(
355 Stream.filter((l) => l.name === name),
356 Stream.runCollect,
357 Effect.map(
358 (chunk): ObservedLocation | undefined =>
359 Array.from(chunk)
360 .sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? ""))
361 .at(0) as ObservedLocation | undefined,
362 ),
363 );
364
365 const resolveName = (id: string, name: string | undefined) =>
366 Effect.gen(function* () {
367 if (name) return name;
368 return yield* createPhysicalName({ id, lowercase: true });
369 });
370
371 const sameNetworks = (
372 observed: ReadonlyArray<LocationNetwork>,
373 desired: ReadonlyArray<LocationNetwork>,
374 ): boolean =>
375 arrayEqualsUnordered(
376 observed.map((n) => n.network),
377 desired.map((n) => n.network),
378 );
379
380 /**
381 * Endpoints are a deeply nested object whose server echo includes extra
382 * `null`/default fields. Compare only the fields the caller declared.
383 */
384 const sameEndpoints = (
385 observed: ObservedLocation["endpoints"],
386 desired: LocationEndpoints,
387 ): boolean => {
388 if (!observed) return false;
389 const sameNetworkList = (
390 o: ReadonlyArray<{ network: string }> | null | undefined,
391 d: ReadonlyArray<{ network: string }> | null | undefined,
392 ) =>
393 d === undefined ||
394 arrayEqualsUnordered(
395 (o ?? []).map((n) => n.network),
396 (d ?? []).map((n) => n.network),
397 );
398 const sameToggle = (o: boolean | null | undefined, d: boolean | undefined) =>
399 d === undefined || (o ?? false) === d;
400 return (
401 sameToggle(observed.doh.enabled, desired.doh.enabled) &&
402 sameToggle(observed.doh.requireToken, desired.doh.requireToken) &&
403 sameNetworkList(observed.doh.networks, desired.doh.networks) &&
404 sameToggle(observed.dot.enabled, desired.dot.enabled) &&
405 sameNetworkList(observed.dot.networks, desired.dot.networks) &&
406 sameToggle(observed.ipv4.enabled, desired.ipv4.enabled) &&
407 sameToggle(observed.ipv6.enabled, desired.ipv6.enabled) &&
408 sameNetworkList(observed.ipv6.networks, desired.ipv6.networks)
409 );
410 };
411
412 type ListedLocation = NonNullable<zeroTrust.ListGatewayLocationsResponse["result"]>[number];
413
414 const toAttributes = (
415 location: ObservedLocation | zeroTrust.UpdateGatewayLocationResponse | ListedLocation,
416 accountId: string,
417 ): LocationAttributes => ({
418 locationId: location.id ?? "",
419 accountId,
420 name: location.name ?? "",
421 clientDefault: location.clientDefault ?? false,
422 ecsSupport: location.ecsSupport ?? false,
423 dohSubdomain: location.dohSubdomain ?? undefined,
424 ip: location.ip ?? undefined,
425 ipv4Destination: location.ipv4Destination ?? undefined,
426 dnsDestinationIpsId: location.dnsDestinationIpsId ?? undefined,
427 networks: (location.networks ?? []).map((n) => ({ network: n.network })),
428 createdAt: location.createdAt ?? undefined,
429 updatedAt: location.updatedAt ?? undefined,
430 });