@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, 04:45 UTC

main
ts 312 lines 10 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 * as Effect from "effect/Effect";
7 import * as Predicate from "effect/Predicate";
8 import * as Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 const TypeId = "Cloudflare.Devices.DexTest" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * What the WARP client probes when the test runs.
17 */
18 export interface DeviceDexTestData {
19 /**
20 * The URL (for `http` tests) or hostname/IP (for `traceroute` tests)
21 * to probe.
22 */
23 host: string;
24 /** The kind of synthetic test the WARP client runs. */
25 kind: "http" | "traceroute";
26 /** The HTTP method to use — only `GET` is supported. */
27 method?: "GET" | (string & {});
28 }
29
30 /**
31 * A device-profile (DEX rule) targeted by the test.
32 */
33 export interface DeviceDexTestTargetPolicy {
34 /** The id of the device settings profile. */
35 id: string;
36 /** Whether the profile is the account default. */
37 default?: boolean;
38 /** The name of the device settings profile. */
39 name?: string;
40 }
41
42 export interface DeviceDexTestProps {
43 /**
44 * Name of the DEX test. Must be unique within the account. If omitted,
45 * a unique name is generated from the app, stage, and logical ID.
46 * @default ${app}-${stage}-${id}
47 */
48 name?: string;
49 /**
50 * The synthetic probe the WARP client runs.
51 */
52 data: DeviceDexTestData;
53 /**
54 * How often the test runs, as a duration string (e.g. `0h30m0s`).
55 */
56 interval: string;
57 /**
58 * Whether the test is active.
59 * @default true
60 */
61 enabled?: boolean;
62 /**
63 * Additional details about the test.
64 */
65 description?: string;
66 /**
67 * Device settings profiles (DEX rules) targeted by this test.
68 */
69 targetPolicies?: DeviceDexTestTargetPolicy[];
70 /**
71 * Whether the test only runs for devices matching `targetPolicies`.
72 */
73 targeted?: boolean;
74 }
75
76 export type DeviceDexTestAttributes = {
77 /** API UUID of the DEX test. */
78 testId: string;
79 /** Account that owns the test. */
80 accountId: string;
81 /** Observed test name. */
82 name: string;
83 /** Observed probe configuration. */
84 data: DeviceDexTestData;
85 /** Observed run interval. */
86 interval: string;
87 /** Whether the test is active. */
88 enabled: boolean;
89 /** Observed description, if any. */
90 description: string | undefined;
91 };
92
93 export type DeviceDexTest = Resource<
94 TypeId,
95 DeviceDexTestProps,
96 DeviceDexTestAttributes,
97 never,
98 Providers
99 >;
100
101 /**
102 * A Cloudflare Zero Trust **DEX synthetic test** — an HTTP or traceroute
103 * probe that enrolled WARP devices run on a schedule so the Digital
104 * Experience Monitoring dashboard can chart reachability and latency to
105 * your critical applications.
106 *
107 * Requires the DEX entitlement on the account (the API rejects writes
108 * with `Forbidden` / `dex.api.entitlements.missing` otherwise).
109 * ### Creating a DEX test
110 * **Example:** HTTP probe every 30 minutes
111 * ```typescript
112 * const test = yield* Cloudflare.Devices.DeviceDexTest("AppHealth", {
113 * data: { host: "https://app.example.com/health", kind: "http", method: "GET" },
114 * interval: "0h30m0s",
115 * description: "Internal app reachability",
116 * });
117 * ```
118 *
119 * **Example:** Traceroute probe targeting specific device profiles
120 * ```typescript
121 * const trace = yield* Cloudflare.Devices.DeviceDexTest("OriginTrace", {
122 * data: { host: "203.0.113.10", kind: "traceroute" },
123 * interval: "0h30m0s",
124 * targeted: true,
125 * targetPolicies: [{ id: profile.policyId }],
126 * });
127 * ```
128 *
129 * @see https://developers.cloudflare.com/cloudflare-one/insights/dex/tests/
130 *
131 * @resource
132 * @product Devices
133 * @category Cloudflare One (Zero Trust)
134 */
135 export const DeviceDexTest = Resource<DeviceDexTest>(TypeId);
136
137 /**
138 * Returns true if the given value is a DeviceDexTest resource.
139 */
140 export const isDeviceDexTest = (value: unknown): value is DeviceDexTest =>
141 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
142
143 export const DeviceDexTestProvider = () =>
144 Provider.succeed(DeviceDexTest, {
145 stables: ["testId", "accountId"],
146
147 // Account-scoped collection: paginate the DEX tests list and hydrate each
148 // row (which already carries the full read shape) into Attributes. DEX
149 // requires the Digital Experience Monitoring entitlement; on unentitled
150 // accounts the list rejects with the typed `Forbidden`
151 // (dex.api.entitlements.missing), so treat that as "nothing to enumerate".
152 list: Effect.fn(function* () {
153 const { accountId } = yield* yield* CloudflareEnvironment;
154 return yield* zeroTrust.listDeviceDexTests.pages({ accountId }).pipe(
155 Stream.runCollect,
156 Effect.map((chunk) =>
157 Array.from(chunk).flatMap((page) =>
158 (page.result ?? [])
159 .filter((t) => t.testId != null)
160 .map((t) => toAttributes(t, accountId)),
161 ),
162 ),
163 Effect.catchTag("Forbidden", () => Effect.succeed([])),
164 );
165 }),
166
167 read: Effect.fn(function* ({ id, output, olds }) {
168 const { accountId } = yield* yield* CloudflareEnvironment;
169 const acct = output?.accountId ?? accountId;
170
171 if (output?.testId) {
172 const observed = yield* observeTest(acct, output.testId);
173 return observed ? toAttributes(observed, acct) : undefined;
174 }
175
176 // Cold lookup: DEX test names are unique per account, but carry no
177 // ownership markers — brand the match `Unowned`.
178 const name = yield* createTestName(id, olds?.name);
179 const match = yield* findByName(acct, name);
180 if (match) return Unowned(toAttributes(match, acct));
181 return undefined;
182 }),
183
184 reconcile: Effect.fn(function* ({ id, news, output }) {
185 const { accountId } = yield* yield* CloudflareEnvironment;
186 const name = yield* createTestName(id, news.name);
187
188 // 1. Observe — cached id is a hint; fall back to a name scan.
189 let observed = output?.testId ? yield* observeTest(accountId, output.testId) : undefined;
190 if (!observed) {
191 observed = yield* findByName(accountId, name);
192 }
193
194 // 2. Ensure — create when missing.
195 if (!observed) {
196 const created = yield* zeroTrust.createDeviceDexTest({
197 accountId,
198 name,
199 enabled: news.enabled ?? true,
200 interval: news.interval,
201 data: encodeData(news.data),
202 ...(news.description !== undefined ? { description: news.description } : {}),
203 ...(news.targeted !== undefined ? { targeted: news.targeted } : {}),
204 ...(news.targetPolicies !== undefined ? { targetPolicies: news.targetPolicies } : {}),
205 });
206 return toAttributes(created, accountId);
207 }
208
209 // 3. Sync — PUT the full desired state when the observed state
210 // differs; skip the call on a no-op.
211 const dirty =
212 (observed.name ?? "") !== name ||
213 (observed.interval ?? "") !== news.interval ||
214 (observed.enabled ?? true) !== (news.enabled ?? true) ||
215 (observed.description ?? undefined) !== news.description ||
216 !sameData(observed.data, news.data);
217 if (!dirty) {
218 return toAttributes(observed, accountId);
219 }
220 const updated = yield* zeroTrust.updateDeviceDexTest({
221 accountId,
222 dexTestId: observed.testId!,
223 name,
224 enabled: news.enabled ?? true,
225 interval: news.interval,
226 data: encodeData(news.data),
227 ...(news.description !== undefined ? { description: news.description } : {}),
228 ...(news.targeted !== undefined ? { targeted: news.targeted } : {}),
229 ...(news.targetPolicies !== undefined ? { targetPolicies: news.targetPolicies } : {}),
230 });
231 return toAttributes(updated, accountId);
232 }),
233
234 delete: Effect.fn(function* ({ output }) {
235 yield* zeroTrust
236 .deleteDeviceDexTest({
237 accountId: output.accountId,
238 dexTestId: output.testId,
239 })
240 .pipe(Effect.catchTag("DexTestNotFound", () => Effect.void));
241 }),
242 });
243
244 /**
245 * Structural shape shared by get/list/create/update responses.
246 */
247 type ObservedDexTest = {
248 data: {
249 host: string;
250 kind: "http" | "traceroute" | (string & {});
251 method?: "GET" | (string & {}) | null;
252 };
253 enabled: boolean;
254 interval: string;
255 name: string;
256 description?: string | null;
257 testId?: string | null;
258 };
259
260 /**
261 * Read a DEX test by id, mapping "gone" to `undefined`.
262 */
263 const observeTest = (accountId: string, dexTestId: string) =>
264 zeroTrust
265 .getDeviceDexTest({ accountId, dexTestId })
266 .pipe(Effect.catchTag("DexTestNotFound", () => Effect.undefined));
267
268 /**
269 * Find a DEX test by exact name (names are unique per account).
270 */
271 const findByName = (accountId: string, name: string) =>
272 zeroTrust
273 .listDeviceDexTests({ accountId })
274 .pipe(
275 Effect.map((list) => (list.result ?? []).find((t) => t.name === name && t.testId != null)),
276 );
277
278 const createTestName = (id: string, name: string | undefined) =>
279 Effect.gen(function* () {
280 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
281 });
282
283 const encodeData = (
284 data: DeviceDexTestData,
285 ): {
286 host: string;
287 kind: "http" | "traceroute";
288 method?: "GET" | (string & {});
289 } => ({
290 host: data.host,
291 kind: data.kind,
292 ...(data.method !== undefined ? { method: data.method } : {}),
293 });
294
295 const sameData = (observed: ObservedDexTest["data"], desired: DeviceDexTestData): boolean =>
296 observed.host === desired.host &&
297 observed.kind === desired.kind &&
298 (observed.method ?? undefined) === desired.method;
299
300 const toAttributes = (test: ObservedDexTest, accountId: string): DeviceDexTestAttributes => ({
301 testId: test.testId ?? "",
302 accountId,
303 name: test.name,
304 data: {
305 host: test.data.host,
306 kind: test.data.kind === "traceroute" ? "traceroute" : "http",
307 ...(test.data.method != null ? { method: test.data.method } : {}),
308 },
309 interval: test.interval,
310 enabled: test.enabled,
311 description: test.description ?? undefined,
312 });