@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 282 lines 10.3 KB
Raw
1 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { arrayEqualsUnordered } from "alchemy/Util/equal";
8 import * as Effect from "effect/Effect";
9 import * as Predicate from "effect/Predicate";
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.ProxyEndpoint" as const;
15 type TypeId = typeof TypeId;
16
17 /**
18 * The kind of proxy endpoint. `ip` endpoints admit traffic from a source
19 * CIDR allowlist (Enterprise only); `identity` endpoints authenticate
20 * per-user. Immutable — changing the kind triggers a replacement.
21 */
22 export type ProxyEndpointKind = "ip" | "identity";
23
24 export interface ProxyEndpointProps {
25 /**
26 * Display name for the proxy endpoint. Used as a stable identifier so
27 * the provider can locate it by name during adoption / state recovery.
28 * If omitted, a unique name is generated from the app, stage, and
29 * logical ID.
30 *
31 * @default ${app}-${stage}-${id}
32 */
33 name?: string;
34 /**
35 * The proxy endpoint kind. `ip` endpoints (source-CIDR allowlist)
36 * require an Enterprise plan; `identity` endpoints work on all Zero
37 * Trust plans. Immutable — changing the kind triggers a replacement.
38 *
39 * @default "ip"
40 */
41 kind?: ProxyEndpointKind;
42 /**
43 * Source CIDRs allowed to connect through the endpoint (e.g.
44 * `203.0.113.1/32`). Required for (and only meaningful on) `ip`-kind
45 * endpoints. Mutable — patched in place.
46 */
47 ips?: string[];
48 }
49
50 export interface ProxyEndpointAttributes {
51 /** UUID of the proxy endpoint, assigned by Cloudflare. */
52 proxyEndpointId: string;
53 /** Cloudflare account that owns the proxy endpoint. */
54 accountId: string;
55 /** Display name of the proxy endpoint. */
56 name: string;
57 /** The proxy endpoint kind. */
58 kind: ProxyEndpointKind;
59 /** Source CIDR allowlist (empty for identity-kind endpoints). */
60 ips: string[];
61 /**
62 * Server-assigned subdomain. The PAC-file proxy hostname is
63 * `<subdomain>.proxy.cloudflare-gateway.com`.
64 */
65 subdomain: string | undefined;
66 /** ISO8601 creation timestamp. */
67 createdAt: string | undefined;
68 /** ISO8601 last-update timestamp. */
69 updatedAt: string | undefined;
70 }
71
72 export type ProxyEndpoint = Resource<
73 TypeId,
74 ProxyEndpointProps,
75 ProxyEndpointAttributes,
76 never,
77 Providers
78 >;
79
80 /**
81 * A Cloudflare Zero Trust Gateway proxy endpoint — an agentless HTTP
82 * proxy for forwarding traffic to Gateway without installing the WARP
83 * client, typically wired up via a PAC file pointing at the endpoint's
84 * server-assigned `subdomain`.
85 *
86 * `ip`-kind endpoints admit traffic from a source-CIDR allowlist and
87 * require an Enterprise plan (Cloudflare error code 2009 otherwise);
88 * `identity`-kind endpoints authenticate individual users and work on all
89 * Zero Trust plans. The kind is immutable; name and `ips` converge in
90 * place. Accounts are limited to a small number of proxy endpoints, so
91 * prefer reusing one per account.
92 * ### Creating a Proxy Endpoint
93 * **Example:** Identity-based endpoint (all plans)
94 * ```typescript
95 * const proxy = yield* Cloudflare.Gateway.ProxyEndpoint("UserProxy", {
96 * kind: "identity",
97 * });
98 * // PAC file target:
99 * const host = `${proxy.subdomain}.proxy.cloudflare-gateway.com`;
100 * ```
101 *
102 * **Example:** IP allowlist endpoint (Enterprise)
103 * ```typescript
104 * const proxy = yield* Cloudflare.Gateway.ProxyEndpoint("OfficeProxy", {
105 * kind: "ip",
106 * ips: ["203.0.113.1/32"],
107 * });
108 * ```
109 *
110 * @see https://developers.cloudflare.com/cloudflare-one/connections/connect-devices/agentless/pac-files/
111 *
112 * @resource
113 * @product Gateway
114 * @category Cloudflare One (Zero Trust)
115 */
116 export const ProxyEndpoint = Resource<ProxyEndpoint>(TypeId);
117
118 /**
119 * Returns true if the given value is a ProxyEndpoint resource.
120 */
121 export const isProxyEndpoint = (value: unknown): value is ProxyEndpoint =>
122 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
123
124 export const ProxyEndpointProvider = () =>
125 Provider.succeed(ProxyEndpoint, {
126 stables: ["proxyEndpointId", "accountId", "kind", "subdomain", "createdAt"],
127
128 diff: Effect.fn(function* ({ olds = {}, news, output }) {
129 const { accountId } = yield* yield* CloudflareEnvironment;
130 if (!isResolved(news)) return undefined;
131 if ((output?.accountId ?? accountId) !== accountId) {
132 return { action: "replace" } as const;
133 }
134 // The endpoint kind is immutable on Cloudflare's side.
135 const oldKind = output?.kind ?? (olds as ProxyEndpointProps).kind ?? undefined;
136 if (oldKind !== undefined && oldKind !== (news.kind ?? "ip")) {
137 return { action: "replace" } as const;
138 }
139 return undefined;
140 }),
141
142 read: Effect.fn(function* ({ id, output, olds }) {
143 const { accountId } = yield* yield* CloudflareEnvironment;
144 const acct = output?.accountId ?? accountId;
145
146 // Owned path — refresh by the cached endpoint id.
147 if (output?.proxyEndpointId) {
148 const observed = yield* getEndpoint(acct, output.proxyEndpointId);
149 if (observed) return toAttributes(observed, acct);
150 }
151
152 // Cold read — locate by deterministic name. Proxy endpoints carry no
153 // ownership markers, so report the match as Unowned to gate adoption.
154 const name = yield* resolveName(id, olds?.name ?? output?.name);
155 const match = yield* findByName(acct, name);
156 if (match) return Unowned(toAttributes(match, acct));
157 return undefined;
158 }),
159
160 reconcile: Effect.fn(function* ({ id, news, output }) {
161 const { accountId } = yield* yield* CloudflareEnvironment;
162 const name = yield* resolveName(id, news.name);
163 const kind = news.kind ?? "ip";
164
165 // 1. Observe — the cached id is a hint; fall back to a name scan.
166 // Accounts are limited to very few proxy endpoints, so converging
167 // onto an existing same-named endpoint matters more than usual.
168 let observed = output?.proxyEndpointId
169 ? yield* getEndpoint(accountId, output.proxyEndpointId)
170 : undefined;
171 if (!observed) {
172 observed = yield* findByName(accountId, name);
173 }
174
175 // 2. Ensure — create with the full desired body when missing.
176 // `ip`-kind endpoints on a non-Enterprise account fail with the
177 // typed entitlement error IpProxyEndpointsRequireEnterprise
178 // (Cloudflare code 2009), which propagates.
179 if (!observed) {
180 observed = yield* zeroTrust.createGatewayProxyEndpoint({
181 accountId,
182 name,
183 kind,
184 ...(kind === "ip" ? { ips: news.ips ?? [] } : {}),
185 });
186 }
187
188 // 3. Sync — diff observed name/ips against desired and PATCH only
189 // the delta; skip the call entirely on a no-op. `ips` compares as
190 // an unordered set and only applies to ip-kind endpoints.
191 const observedIps = observedIpsOf(observed);
192 const dirty =
193 observed.name !== name ||
194 (kind === "ip" && news.ips !== undefined && !arrayEqualsUnordered(observedIps, news.ips));
195 if (dirty) {
196 observed = yield* zeroTrust.patchGatewayProxyEndpoint({
197 accountId,
198 proxyEndpointId: observed.id ?? "",
199 name,
200 ...(kind === "ip" && news.ips !== undefined ? { ips: news.ips } : {}),
201 });
202 }
203
204 return toAttributes(observed, accountId);
205 }),
206
207 delete: Effect.fn(function* ({ output }) {
208 // A missing endpoint (ProxyEndpointNotFound, code 2002) means we're
209 // done.
210 yield* zeroTrust
211 .deleteGatewayProxyEndpoint({
212 accountId: output.accountId,
213 proxyEndpointId: output.proxyEndpointId,
214 })
215 .pipe(Effect.catchTag("ProxyEndpointNotFound", () => Effect.void));
216 }),
217
218 // Account-scoped collection: the proxy-endpoints list op returns each
219 // endpoint's full body, so no per-item hydration is needed. Exhaustively
220 // paginate (`.items` flattens `result` across pages) and map straight into
221 // the `read` Attributes shape.
222 list: Effect.fn(function* () {
223 const { accountId } = yield* yield* CloudflareEnvironment;
224 return yield* zeroTrust.listGatewayProxyEndpoints.items({ accountId }).pipe(
225 Stream.map((e) => toAttributes(e as ObservedEndpoint, accountId)),
226 Stream.runCollect,
227 Effect.map((chunk) => Array.from(chunk)),
228 );
229 }),
230 });
231
232 type ObservedEndpoint = zeroTrust.GetGatewayProxyEndpointResponse;
233
234 /**
235 * Read a proxy endpoint by id, mapping "gone" (`ProxyEndpointNotFound`,
236 * Cloudflare error code 2002) to `undefined`.
237 */
238 const getEndpoint = (accountId: string, proxyEndpointId: string) =>
239 zeroTrust.getGatewayProxyEndpoint({ accountId, proxyEndpointId }).pipe(
240 Effect.map((e): ObservedEndpoint | undefined => e),
241 Effect.catchTag("ProxyEndpointNotFound", () => Effect.undefined),
242 );
243
244 /**
245 * Find a proxy endpoint by exact name. Pick the oldest match for
246 * determinism.
247 */
248 const findByName = (accountId: string, name: string) =>
249 zeroTrust.listGatewayProxyEndpoints.items({ accountId }).pipe(
250 Stream.filter((e) => e.name === name),
251 Stream.runCollect,
252 Effect.map(
253 (chunk): ObservedEndpoint | undefined =>
254 Array.from(chunk)
255 .sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? ""))
256 .at(0) as ObservedEndpoint | undefined,
257 ),
258 );
259
260 const resolveName = (id: string, name: string | undefined) =>
261 Effect.gen(function* () {
262 if (name) return name;
263 return yield* createPhysicalName({ id, lowercase: true });
264 });
265
266 /**
267 * Identity-kind endpoints report `ips: null` on the wire (previously `[]`),
268 * so a key-presence check is not enough — only a real array counts.
269 */
270 const observedIpsOf = (endpoint: ObservedEndpoint): string[] =>
271 "ips" in endpoint && Array.isArray(endpoint.ips) ? [...endpoint.ips] : [];
272
273 const toAttributes = (endpoint: ObservedEndpoint, accountId: string): ProxyEndpointAttributes => ({
274 proxyEndpointId: endpoint.id ?? "",
275 accountId,
276 name: endpoint.name,
277 kind: (endpoint.kind ?? "ip") as ProxyEndpointKind,
278 ips: observedIpsOf(endpoint),
279 subdomain: endpoint.subdomain ?? undefined,
280 createdAt: endpoint.createdAt ?? undefined,
281 updatedAt: endpoint.updatedAt ?? undefined,
282 });