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

main
ts 270 lines 9.08 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.ManagedNetwork" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * Detection configuration for a managed network: the WARP client opens a
17 * TLS connection to `tlsSockaddr` and (optionally) verifies the
18 * certificate's SHA-256 fingerprint to decide whether the device is on
19 * the network.
20 */
21 export interface DeviceManagedNetworkConfig {
22 /**
23 * A network address of the form `host:port` that the WARP client will
24 * probe over TLS to detect the network (e.g. `"192.0.2.1:443"`).
25 */
26 tlsSockaddr: string;
27 /**
28 * The SHA-256 fingerprint (64 hexadecimal characters) of the TLS
29 * certificate served at {@link tlsSockaddr}. When set, the client only
30 * considers the network detected if the certificate matches.
31 */
32 sha256?: string;
33 }
34
35 export interface DeviceManagedNetworkProps {
36 /**
37 * Name of the managed network. Must be unique within the account. If
38 * omitted, a unique name is generated from the app, stage, and logical
39 * ID.
40 * @default ${app}-${stage}-${id}
41 */
42 name?: string;
43 /**
44 * TLS detection endpoint for the network. Mutable — updated in place.
45 */
46 config: DeviceManagedNetworkConfig;
47 }
48
49 export type DeviceManagedNetworkAttributes = {
50 /** API UUID of the managed network. */
51 networkId: string;
52 /** Account that owns the managed network. */
53 accountId: string;
54 /** Observed network name. */
55 name: string;
56 /** The type of managed network — always `tls`. */
57 type: "tls";
58 /** Observed TLS detection configuration. */
59 config: DeviceManagedNetworkConfig;
60 };
61
62 export type DeviceManagedNetwork = Resource<
63 TypeId,
64 DeviceManagedNetworkProps,
65 DeviceManagedNetworkAttributes,
66 never,
67 Providers
68 >;
69
70 /**
71 * A Cloudflare Zero Trust **device managed network** — a TLS endpoint the
72 * WARP client probes to detect whether the device is on a known network.
73 * Device profiles can then `match` on `network` to apply different WARP
74 * settings on trusted networks.
75 *
76 * Name and config are mutable in place (PUT). `tls` is the only network
77 * type Cloudflare supports.
78 * ### Creating a managed network
79 * **Example:** Detect the office network by TLS fingerprint
80 * ```typescript
81 * const network = yield* Cloudflare.Devices.DeviceManagedNetwork("Office", {
82 * config: {
83 * tlsSockaddr: "192.0.2.1:443",
84 * sha256:
85 * "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c",
86 * },
87 * });
88 * ```
89 *
90 * **Example:** Use the network in a custom device profile
91 * ```typescript
92 * yield* Cloudflare.Devices.DeviceCustomProfile("OnPrem", {
93 * match: `network == "${network.name}"`,
94 * precedence: 100,
95 * serviceModeV2: { mode: "proxy", port: 3000 },
96 * });
97 * ```
98 *
99 * @see https://developers.cloudflare.com/cloudflare-one/connections/connect-devices/warp/configure-warp/managed-networks/
100 *
101 * @resource
102 * @product Devices
103 * @category Cloudflare One (Zero Trust)
104 */
105 export const DeviceManagedNetwork = Resource<DeviceManagedNetwork>(TypeId);
106
107 /**
108 * Returns true if the given value is a DeviceManagedNetwork resource.
109 */
110 export const isDeviceManagedNetwork = (value: unknown): value is DeviceManagedNetwork =>
111 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
112
113 export const DeviceManagedNetworkProvider = () =>
114 Provider.succeed(DeviceManagedNetwork, {
115 stables: ["networkId", "accountId", "type"],
116
117 // Account collection: managed networks are account-scoped and the
118 // distilled list op paginates (items: "result"). Enumerate every page
119 // and hydrate into the exact `read` Attributes shape via `toAttributes`.
120 list: Effect.fn(function* () {
121 const { accountId } = yield* yield* CloudflareEnvironment;
122 return yield* zeroTrust.listDeviceNetworks.pages({ accountId }).pipe(
123 Stream.runCollect,
124 Effect.map((chunk) =>
125 Array.from(chunk).flatMap((page) =>
126 (page.result ?? [])
127 .filter((n) => n.networkId != null)
128 .map((n) => toAttributes(n, accountId)),
129 ),
130 ),
131 );
132 }),
133
134 read: Effect.fn(function* ({ id, output, olds }) {
135 const { accountId } = yield* yield* CloudflareEnvironment;
136 const acct = output?.accountId ?? accountId;
137
138 // Owned path: refresh by our persisted network id.
139 if (output?.networkId) {
140 const observed = yield* observeNetwork(acct, output.networkId);
141 return observed ? toAttributes(observed, acct) : undefined;
142 }
143
144 // Cold lookup: names are unique per account, so an exact match
145 // identifies the network — but it carries no ownership markers, so
146 // brand it `Unowned` and let the engine gate takeover behind the
147 // adopt policy.
148 const name = yield* createNetworkName(id, olds?.name);
149 const match = yield* findByName(acct, name);
150 if (match) return Unowned(toAttributes(match, acct));
151 return undefined;
152 }),
153
154 reconcile: Effect.fn(function* ({ id, news, output }) {
155 const { accountId } = yield* yield* CloudflareEnvironment;
156 const name = yield* createNetworkName(id, news.name);
157
158 // 1. Observe — the network id cached on `output` is a hint, not a
159 // guarantee. Names are unique per account, so also scan by name
160 // to converge on a network created by a crashed prior run.
161 let observed = output?.networkId
162 ? yield* observeNetwork(accountId, output.networkId)
163 : undefined;
164 if (!observed) {
165 observed = yield* findByName(accountId, name);
166 }
167
168 // 2. Ensure — create when missing.
169 if (!observed) {
170 const created = yield* zeroTrust.createDeviceNetwork({
171 accountId,
172 name,
173 type: "tls",
174 config: encodeConfig(news.config),
175 });
176 return toAttributes(created, accountId);
177 }
178
179 // 3. Sync — PUT name/config when the observed state differs; skip
180 // the call entirely on a no-op.
181 const dirty = (observed.name ?? "") !== name || !sameConfig(observed.config, news.config);
182 if (!dirty) {
183 return toAttributes(observed, accountId);
184 }
185 const updated = yield* zeroTrust.updateDeviceNetwork({
186 accountId,
187 networkId: observed.networkId!,
188 name,
189 type: "tls",
190 config: encodeConfig(news.config),
191 });
192 return toAttributes(updated, accountId);
193 }),
194
195 delete: Effect.fn(function* ({ output }) {
196 // Cloudflare's delete is already idempotent (200 on a missing
197 // network); the typed catch covers the documented error path too.
198 yield* zeroTrust
199 .deleteDeviceNetwork({
200 accountId: output.accountId,
201 networkId: output.networkId,
202 })
203 .pipe(Effect.catchTag("DeviceNetworkNotFound", () => Effect.void));
204 }),
205 });
206
207 /**
208 * Structural shape shared by get/list/create/update responses.
209 */
210 type ObservedNetwork = {
211 config?: { tlsSockaddr: string; sha256?: string | null } | null;
212 name?: string | null;
213 networkId?: string | null;
214 type?: "tls" | (string & {}) | null;
215 };
216
217 /**
218 * Read a managed network by id, mapping "gone" (`DeviceNetworkNotFound`,
219 * Cloudflare error code 2053) to `undefined`.
220 */
221 const observeNetwork = (accountId: string, networkId: string) =>
222 zeroTrust
223 .getDeviceNetwork({ accountId, networkId })
224 .pipe(Effect.catchTag("DeviceNetworkNotFound", () => Effect.undefined));
225
226 /**
227 * Find a managed network by exact name. Names are unique per account.
228 */
229 const findByName = (accountId: string, name: string) =>
230 zeroTrust
231 .listDeviceNetworks({ accountId })
232 .pipe(Effect.map((list) => list.result.find((n) => n.name === name && n.networkId != null)));
233
234 const createNetworkName = (id: string, name: string | undefined) =>
235 Effect.gen(function* () {
236 // Cloudflare caps managed network names at 50 characters.
237 return name ?? (yield* createPhysicalName({ id, lowercase: true, maxLength: 50 }));
238 });
239
240 const encodeConfig = (
241 config: DeviceManagedNetworkConfig,
242 ): { tlsSockaddr: string; sha256?: string } => {
243 const out: { tlsSockaddr: string; sha256?: string } = {
244 tlsSockaddr: config.tlsSockaddr,
245 };
246 if (config.sha256 !== undefined) out.sha256 = config.sha256;
247 return out;
248 };
249
250 const sameConfig = (
251 observed: ObservedNetwork["config"],
252 desired: DeviceManagedNetworkConfig,
253 ): boolean =>
254 observed != null &&
255 observed.tlsSockaddr === desired.tlsSockaddr &&
256 (observed.sha256 ?? undefined) === desired.sha256;
257
258 const toAttributes = (
259 network: ObservedNetwork,
260 accountId: string,
261 ): DeviceManagedNetworkAttributes => ({
262 networkId: network.networkId ?? "",
263 accountId,
264 name: network.name ?? "",
265 type: "tls",
266 config: {
267 tlsSockaddr: network.config?.tlsSockaddr ?? "",
268 sha256: network.config?.sha256 ?? undefined,
269 },
270 });