@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 279 lines 9.73 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 * as Effect from "effect/Effect";
8 import * as Option from "effect/Option";
9 import * as Predicate from "effect/Predicate";
10 import * as Redacted from "effect/Redacted";
11 import * as Stream from "effect/Stream";
12 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
13 import type { Providers } from "../Providers.ts";
14
15 const TypeId = "Cloudflare.Tunnel.WarpConnector" as const;
16 type TypeId = typeof TypeId;
17
18 export interface WarpConnectorProps {
19 /**
20 * User-friendly name for the WARP Connector tunnel. Tunnel names are
21 * unique per account, which makes the name the resource's identity
22 * during adoption and state recovery. Changing it replaces the tunnel.
23 *
24 * @default ${app}-${stage}-${id}
25 */
26 name?: string;
27 }
28
29 export interface WarpConnectorAttributes {
30 /** UUID of the WARP Connector tunnel, assigned by Cloudflare. */
31 tunnelId: string;
32 /** Cloudflare account that owns the tunnel. */
33 accountId: string;
34 /** User-friendly name of the tunnel. */
35 name: string;
36 /**
37 * Status of the tunnel: `inactive` (never run), `degraded`, `healthy`,
38 * or `down`.
39 */
40 status: string | undefined;
41 /** RFC 3339 timestamp of when the tunnel was created. */
42 createdAt: string | undefined;
43 /**
44 * Connector token used to run the WARP Connector on a host
45 * (`warp-cli connector new <token>`). Sensitive — stored redacted.
46 */
47 token: Redacted.Redacted<string>;
48 }
49
50 export type WarpConnector = Resource<
51 TypeId,
52 WarpConnectorProps,
53 WarpConnectorAttributes,
54 never,
55 Providers
56 >;
57
58 /**
59 * A Cloudflare WARP Connector tunnel — a software site-to-site connector
60 * that extends a private network into Cloudflare Zero Trust without
61 * running `cloudflared`.
62 *
63 * The resource manages the tunnel record itself (CRUD); a WARP Connector
64 * host joins it at runtime using the `token` attribute. Pair with
65 * {@link Route} to route private CIDRs through the connector and
66 * {@link VirtualNetwork} to isolate overlapping address space.
67 * ### Creating a WARP Connector
68 * **Example:** Basic WARP Connector tunnel
69 * ```typescript
70 * const connector = yield* Cloudflare.Tunnel.WarpConnector("SiteA", {
71 * name: "site-a-connector",
72 * });
73 * // Provision the host with: warp-cli connector new <Redacted.value(connector.token)>
74 * ```
75 *
76 * **Example:** Route a private network through the connector
77 * ```typescript
78 * yield* Cloudflare.Tunnel.Route("SiteANet", {
79 * tunnelId: connector.tunnelId,
80 * network: "10.8.0.0/16",
81 * });
82 * ```
83 *
84 * ### Renaming
85 * **Example:** Replace with a new name
86 * ```typescript
87 * // Renaming creates a new tunnel with a new tunnelId.
88 * const connector = yield* Cloudflare.Tunnel.WarpConnector("SiteA", {
89 * name: "site-a-connector-v2",
90 * });
91 * ```
92 *
93 * @see https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/private-net/warp-connector/
94 *
95 * @resource
96 * @product Tunnels
97 * @category Cloudflare One (Zero Trust)
98 */
99 export const WarpConnector = Resource<WarpConnector>(TypeId);
100
101 /**
102 * Returns true if the given value is a WarpConnector resource.
103 */
104 export const isWarpConnector = (value: unknown): value is WarpConnector =>
105 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
106
107 export const WarpConnectorProvider = () =>
108 Provider.succeed(WarpConnector, {
109 stables: ["tunnelId", "accountId", "createdAt"],
110
111 diff: Effect.fn(function* ({ olds, news, output }) {
112 const { accountId } = yield* yield* CloudflareEnvironment;
113 if ((output?.accountId ?? accountId) !== accountId) {
114 return { action: "replace" } as const;
115 }
116 if (isResolved(news) && olds !== undefined && olds.name !== news.name) {
117 return { action: "replace" } as const;
118 }
119 return undefined;
120 }),
121
122 read: Effect.fn(function* ({ id, output, olds }) {
123 const { accountId } = yield* yield* CloudflareEnvironment;
124 const acct = output?.accountId ?? accountId;
125
126 // Owned path — refresh by the cached id.
127 if (output?.tunnelId) {
128 const observed = yield* getConnector(acct, output.tunnelId);
129 if (observed) return yield* toAttributes(observed, acct);
130 }
131
132 // Cold read — tunnel names are unique per account, so an exact name
133 // match is the resource's identity. WARP Connector tunnels carry no
134 // ownership markers, so gate adoption behind Unowned.
135 const name = yield* resolveName(id, olds?.name ?? output?.name);
136 const match = yield* findByName(acct, name);
137 if (match) return Unowned(yield* toAttributes(match, acct));
138 return undefined;
139 }),
140
141 // Account collection: the dedicated `/accounts/{id}/warp_connector`
142 // endpoint already scopes to warp_connector tunnels. Paginate
143 // exhaustively, drop soft-deleted tunnels (match `read`), then hydrate
144 // each live tunnel into the exact `read` Attributes shape (token
145 // included). A tunnel deleted out from under us between the list and the
146 // token fetch surfaces as a typed TunnelNotFound — skip it.
147 list: Effect.fn(function* () {
148 const { accountId } = yield* yield* CloudflareEnvironment;
149 const observed = yield* zeroTrust.listTunnelWarpConnectors
150 .pages({ accountId, isDeleted: false })
151 .pipe(
152 Stream.runCollect,
153 Effect.map((chunk) =>
154 Array.from(chunk).flatMap((page) =>
155 (page.result ?? []).filter(
156 (t): t is ObservedConnector & { id: string } =>
157 !t.deletedAt && typeof t.id === "string",
158 ),
159 ),
160 ),
161 );
162 const rows = yield* Effect.forEach(
163 observed,
164 (t) =>
165 toAttributes(t, accountId).pipe(
166 Effect.asSome,
167 Effect.catchTag("TunnelNotFound", () =>
168 Effect.succeed(Option.none<WarpConnectorAttributes>()),
169 ),
170 ),
171 { concurrency: 10 },
172 );
173 return rows.flatMap((row) => (Option.isSome(row) ? [row.value] : []));
174 }),
175
176 reconcile: Effect.fn(function* ({ id, news, output }) {
177 const { accountId } = yield* yield* CloudflareEnvironment;
178 const name = yield* resolveName(id, news.name);
179
180 // 1. Observe — the cached id is a hint, not a guarantee.
181 let observed = output?.tunnelId ? yield* getConnector(accountId, output.tunnelId) : undefined;
182 if (!observed) {
183 observed = yield* findByName(accountId, name);
184 }
185
186 // 2. Ensure — create when missing. Tunnel names are unique per
187 // account, so a racing create surfaces as DuplicateTunnelName
188 // (code 1013): converge by re-reading the tunnel that won.
189 if (!observed) {
190 observed = yield* zeroTrust
191 .createTunnelWarpConnector({ accountId, name })
192 .pipe(
193 Effect.catchTag("DuplicateTunnelName", (error) =>
194 findByName(accountId, name).pipe(
195 Effect.flatMap((existing) =>
196 existing ? Effect.succeed(existing) : Effect.fail(error),
197 ),
198 ),
199 ),
200 );
201 }
202
203 // 3. Sync — rename via PATCH only when the observed name differs.
204 if ((observed.name ?? undefined) !== name) {
205 observed = yield* zeroTrust.patchTunnelWarpConnector({
206 accountId,
207 tunnelId: observed.id!,
208 name,
209 });
210 }
211
212 return yield* toAttributes(observed, accountId);
213 }),
214
215 delete: Effect.fn(function* ({ output }) {
216 // Deleting requires all connector sessions to be down — true for
217 // tunnels never joined by a host. A missing tunnel (TunnelNotFound,
218 // code 1002) means we're done.
219 yield* zeroTrust
220 .deleteTunnelWarpConnector({
221 accountId: output.accountId,
222 tunnelId: output.tunnelId,
223 })
224 .pipe(Effect.catchTag("TunnelNotFound", () => Effect.void));
225 }),
226 });
227
228 interface ObservedConnector {
229 id?: string;
230 name?: string | null;
231 status?: "inactive" | "degraded" | "healthy" | "down" | null;
232 createdAt?: string | null;
233 deletedAt?: string | null;
234 }
235
236 /**
237 * Read a WARP Connector tunnel by id, mapping "gone" (`TunnelNotFound`,
238 * Cloudflare error code 1002) and soft-deleted tunnels to `undefined`.
239 */
240 const getConnector = (accountId: string, tunnelId: string) =>
241 zeroTrust.getTunnelWarpConnector({ accountId, tunnelId }).pipe(
242 Effect.map((t): ObservedConnector | undefined => (t.deletedAt ? undefined : t)),
243 Effect.catchTag("TunnelNotFound", () => Effect.undefined),
244 );
245
246 /**
247 * Find a live WARP Connector tunnel by exact name. Tunnel names are
248 * unique per account so at most one live tunnel can match.
249 */
250 const findByName = (accountId: string, name: string) =>
251 zeroTrust.listTunnelWarpConnectors.items({ accountId, name, isDeleted: false }).pipe(
252 Stream.filter(
253 (t): t is ObservedConnector & { id: string } =>
254 t.name === name && !t.deletedAt && typeof t.id === "string",
255 ),
256 Stream.runHead,
257 Effect.map(Option.getOrUndefined),
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 const toAttributes = Effect.fn(function* (tunnel: ObservedConnector, accountId: string) {
267 const token = yield* zeroTrust.getTunnelWarpConnectorToken({
268 accountId,
269 tunnelId: tunnel.id!,
270 });
271 return {
272 tunnelId: tunnel.id!,
273 accountId,
274 name: tunnel.name ?? "",
275 status: tunnel.status ?? undefined,
276 createdAt: tunnel.createdAt ?? undefined,
277 token: Redacted.make(token),
278 } satisfies WarpConnectorAttributes;
279 });