The best way to control Claude Code, Codex and more from any computer or phone
| 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 Predicate from "effect/Predicate"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 11 | import type { Providers } from "../Providers.ts"; |
| 12 | |
| 13 | const TypeId = "Cloudflare.Devices.PostureRule" as const; |
| 14 | type TypeId = typeof TypeId; |
| 15 | |
| 16 | /** |
| 17 | * The type of device posture rule, e.g. `os_version`, `firewall`, |
| 18 | * `disk_encryption`, or a third-party service-to-service integration type |
| 19 | * like `crowdstrike_s2s` (which requires a posture integration's |
| 20 | * `connectionId` in {@link DevicePostureRuleProps.input}). |
| 21 | */ |
| 22 | export type DevicePostureRuleType = zeroTrust.CreateDevicePostureRequest["type"]; |
| 23 | |
| 24 | /** |
| 25 | * The per-type check definition for a posture rule. The accepted shape |
| 26 | * depends on {@link DevicePostureRuleProps.type} — e.g. `os_version` takes |
| 27 | * `{ operatingSystem, operator, version }`, `firewall` takes |
| 28 | * `{ enabled, operatingSystem }`, `disk_encryption` takes |
| 29 | * `{ checkDisks?, requireAll? }`. |
| 30 | */ |
| 31 | export type DevicePostureRuleInput = zeroTrust.CreateDevicePostureRequest["input"]; |
| 32 | |
| 33 | /** |
| 34 | * Platform conditions that scope which devices run the rule. |
| 35 | */ |
| 36 | export type DevicePostureRuleMatch = zeroTrust.CreateDevicePostureRequest["match"]; |
| 37 | |
| 38 | export interface DevicePostureRuleProps { |
| 39 | /** |
| 40 | * Name of the device posture rule. If omitted, a unique name is |
| 41 | * generated from the app, stage, and logical ID. |
| 42 | * @default ${app}-${stage}-${id} |
| 43 | */ |
| 44 | name?: string; |
| 45 | /** |
| 46 | * The type of posture check (e.g. `os_version`, `firewall`, |
| 47 | * `disk_encryption`, `crowdstrike_s2s`). Immutable — changing the type |
| 48 | * triggers a replacement. |
| 49 | */ |
| 50 | type: DevicePostureRuleType; |
| 51 | /** |
| 52 | * A description of the posture rule. |
| 53 | */ |
| 54 | description?: string; |
| 55 | /** |
| 56 | * Polling frequency for the WARP client posture check (e.g. `"5m"`, |
| 57 | * `"1h"`). Minimum `1m`. |
| 58 | * @default "5m" |
| 59 | */ |
| 60 | schedule?: string; |
| 61 | /** |
| 62 | * Expiration time for a posture check result (e.g. `"1h"`). If empty, |
| 63 | * the result remains valid until overwritten by new data from the WARP |
| 64 | * client. |
| 65 | */ |
| 66 | expiration?: string; |
| 67 | /** |
| 68 | * The conditions (platforms) that a device must match for the rule to |
| 69 | * run, e.g. `[{ platform: "mac" }]`. |
| 70 | */ |
| 71 | match?: DevicePostureRuleMatch; |
| 72 | /** |
| 73 | * The per-type value to check against. Shape depends on {@link type}. |
| 74 | */ |
| 75 | input?: DevicePostureRuleInput; |
| 76 | } |
| 77 | |
| 78 | export type DevicePostureRuleAttributes = { |
| 79 | /** API UUID of the posture rule. */ |
| 80 | postureRuleId: string; |
| 81 | /** Account that owns the rule. */ |
| 82 | accountId: string; |
| 83 | /** Observed rule name. */ |
| 84 | name: string; |
| 85 | /** Observed rule type. */ |
| 86 | type: string; |
| 87 | /** Observed description. */ |
| 88 | description: string | undefined; |
| 89 | /** Observed polling schedule. */ |
| 90 | schedule: string | undefined; |
| 91 | /** Observed result expiration. */ |
| 92 | expiration: string | undefined; |
| 93 | /** Observed platform conditions. */ |
| 94 | match: { platform: string | undefined }[] | undefined; |
| 95 | /** Observed per-type check definition. */ |
| 96 | input: unknown; |
| 97 | }; |
| 98 | |
| 99 | export type DevicePostureRule = Resource< |
| 100 | TypeId, |
| 101 | DevicePostureRuleProps, |
| 102 | DevicePostureRuleAttributes, |
| 103 | never, |
| 104 | Providers |
| 105 | >; |
| 106 | |
| 107 | /** |
| 108 | * A Cloudflare Zero Trust **device posture rule** — a periodic check the |
| 109 | * WARP client runs on enrolled devices (OS version, firewall status, disk |
| 110 | * encryption, file presence, or a third-party security provider's |
| 111 | * verdict). Posture results can then gate Access policies and Gateway |
| 112 | * rules. |
| 113 | * |
| 114 | * Everything except `type` is mutable in place (full PUT). Changing |
| 115 | * `type` replaces the rule. |
| 116 | * ### Infrastructure-free checks |
| 117 | * **Example:** Require a minimum Windows version |
| 118 | * ```typescript |
| 119 | * const rule = yield* Cloudflare.Devices.DevicePostureRule("WindowsOsVersion", { |
| 120 | * type: "os_version", |
| 121 | * description: "Require Windows 10.0.19045+", |
| 122 | * match: [{ platform: "windows" }], |
| 123 | * schedule: "5m", |
| 124 | * input: { |
| 125 | * operatingSystem: "windows", |
| 126 | * operator: ">=", |
| 127 | * version: "10.0.19045", |
| 128 | * }, |
| 129 | * }); |
| 130 | * ``` |
| 131 | * |
| 132 | * **Example:** Require the OS firewall to be enabled |
| 133 | * ```typescript |
| 134 | * yield* Cloudflare.Devices.DevicePostureRule("Firewall", { |
| 135 | * type: "firewall", |
| 136 | * match: [{ platform: "windows" }, { platform: "mac" }], |
| 137 | * input: { enabled: true, operatingSystem: "windows" }, |
| 138 | * }); |
| 139 | * ``` |
| 140 | * |
| 141 | * **Example:** Require disk encryption on all drives |
| 142 | * ```typescript |
| 143 | * yield* Cloudflare.Devices.DevicePostureRule("DiskEncryption", { |
| 144 | * type: "disk_encryption", |
| 145 | * match: [{ platform: "mac" }], |
| 146 | * input: { requireAll: true }, |
| 147 | * }); |
| 148 | * ``` |
| 149 | * |
| 150 | * @see https://developers.cloudflare.com/cloudflare-one/identity/devices/ |
| 151 | * |
| 152 | * @resource |
| 153 | * @product Devices |
| 154 | * @category Cloudflare One (Zero Trust) |
| 155 | */ |
| 156 | export const DevicePostureRule = Resource<DevicePostureRule>(TypeId); |
| 157 | |
| 158 | /** |
| 159 | * Returns true if the given value is a DevicePostureRule resource. |
| 160 | */ |
| 161 | export const isDevicePostureRule = (value: unknown): value is DevicePostureRule => |
| 162 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 163 | |
| 164 | export const DevicePostureRuleProvider = () => |
| 165 | Provider.succeed(DevicePostureRule, { |
| 166 | stables: ["postureRuleId", "accountId", "type"], |
| 167 | |
| 168 | list: Effect.fn(function* () { |
| 169 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 170 | // Account-scoped collection: exhaustively paginate the device |
| 171 | // posture rules list and hydrate each into the `read` shape. |
| 172 | return yield* zeroTrust.listDevicePostures.pages({ accountId }).pipe( |
| 173 | Stream.runCollect, |
| 174 | Effect.map((chunk) => |
| 175 | Array.from(chunk).flatMap((page) => |
| 176 | (page.result ?? []).map((rule) => toAttributes(rule, accountId)), |
| 177 | ), |
| 178 | ), |
| 179 | // Account lacks the Zero Trust / device posture entitlement. |
| 180 | Effect.catchTag("Forbidden", () => Effect.succeed([])), |
| 181 | ); |
| 182 | }), |
| 183 | |
| 184 | diff: Effect.fn(function* ({ olds, news, output }) { |
| 185 | if (!isResolved(news)) return undefined; |
| 186 | // `type` is immutable on Cloudflare's side — replace on change. |
| 187 | const oldType = output?.type ?? olds?.type; |
| 188 | if (oldType !== undefined && oldType !== news.type) { |
| 189 | return { action: "replace" } as const; |
| 190 | } |
| 191 | return undefined; |
| 192 | }), |
| 193 | |
| 194 | read: Effect.fn(function* ({ id, output, olds, previous }) { |
| 195 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 196 | const acct = output?.accountId ?? accountId; |
| 197 | |
| 198 | // Owned path: refresh by our persisted rule id. |
| 199 | if (output?.postureRuleId) { |
| 200 | const observed = yield* observeRule(acct, output.postureRuleId); |
| 201 | return observed ? toAttributes(observed, acct) : undefined; |
| 202 | } |
| 203 | |
| 204 | // Cold lookup: recover from lost state by exact name. Posture rules |
| 205 | // carry no ownership markers, so brand the match `Unowned`. |
| 206 | const name = yield* createRuleName(id, olds?.name); |
| 207 | const match = yield* findByName(acct, name); |
| 208 | // A create-first replacement reuses the name: the generation it is |
| 209 | // replacing is not the replacement, so report nothing there yet. |
| 210 | if (match && match.id === previous?.postureRuleId) return undefined; |
| 211 | if (match) return Unowned(toAttributes(match, acct)); |
| 212 | return undefined; |
| 213 | }), |
| 214 | |
| 215 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 216 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 217 | const name = yield* createRuleName(id, news.name); |
| 218 | |
| 219 | // 1. Observe — the rule id cached on `output` is a hint, not a |
| 220 | // guarantee: a missing rule falls through to create. |
| 221 | const observed = output?.postureRuleId |
| 222 | ? yield* observeRule(accountId, output.postureRuleId) |
| 223 | : undefined; |
| 224 | |
| 225 | // 2. Ensure — create when missing. Names are not unique on |
| 226 | // Cloudflare's side, so there is no AlreadyExists race. |
| 227 | if (!observed) { |
| 228 | const created = yield* zeroTrust.createDevicePosture({ |
| 229 | accountId, |
| 230 | name, |
| 231 | type: news.type, |
| 232 | description: news.description, |
| 233 | schedule: news.schedule, |
| 234 | expiration: news.expiration, |
| 235 | match: news.match, |
| 236 | input: news.input, |
| 237 | }); |
| 238 | return toAttributes(created, accountId); |
| 239 | } |
| 240 | |
| 241 | // 3. Sync — the update API is a PUT that requires the full body; |
| 242 | // send everything, but skip the call entirely on a no-op. |
| 243 | const dirty = |
| 244 | (observed.name ?? "") !== name || |
| 245 | (news.description !== undefined && |
| 246 | !sameJSON(denull(observed.description), news.description)) || |
| 247 | (news.schedule !== undefined && denull(observed.schedule) !== news.schedule) || |
| 248 | (news.expiration !== undefined && denull(observed.expiration) !== news.expiration) || |
| 249 | (news.match !== undefined && !sameJSON(normalizeMatch(observed.match), news.match)) || |
| 250 | (news.input !== undefined && !sameJSON(observed.input, news.input)); |
| 251 | if (!dirty) { |
| 252 | return toAttributes(observed, accountId); |
| 253 | } |
| 254 | const updated = yield* zeroTrust.updateDevicePosture({ |
| 255 | accountId, |
| 256 | ruleId: observed.id!, |
| 257 | name, |
| 258 | type: news.type, |
| 259 | description: news.description, |
| 260 | schedule: news.schedule, |
| 261 | expiration: news.expiration, |
| 262 | match: news.match, |
| 263 | input: news.input, |
| 264 | }); |
| 265 | return toAttributes(updated, accountId); |
| 266 | }), |
| 267 | |
| 268 | delete: Effect.fn(function* ({ output }) { |
| 269 | // Cloudflare's delete is already idempotent (200 on a missing |
| 270 | // rule); the typed catch covers the documented 404 path too. |
| 271 | yield* zeroTrust |
| 272 | .deleteDevicePosture({ |
| 273 | accountId: output.accountId, |
| 274 | ruleId: output.postureRuleId, |
| 275 | }) |
| 276 | .pipe(Effect.catchTag("PostureRuleNotFound", () => Effect.void)); |
| 277 | }), |
| 278 | }); |
| 279 | |
| 280 | type ObservedRule = |
| 281 | | zeroTrust.GetDevicePostureResponse |
| 282 | | zeroTrust.CreateDevicePostureResponse |
| 283 | | zeroTrust.UpdateDevicePostureResponse |
| 284 | | zeroTrust.ListDevicePosturesResponse["result"][number]; |
| 285 | |
| 286 | /** |
| 287 | * Read a posture rule by id, mapping "gone" (`PostureRuleNotFound`, |
| 288 | * Cloudflare error code 6024) to `undefined`. |
| 289 | */ |
| 290 | const observeRule = (accountId: string, ruleId: string) => |
| 291 | zeroTrust |
| 292 | .getDevicePosture({ accountId, ruleId }) |
| 293 | .pipe(Effect.catchTag("PostureRuleNotFound", () => Effect.undefined)); |
| 294 | |
| 295 | /** |
| 296 | * Find a posture rule by exact name (oldest-id-first for determinism when |
| 297 | * names collide). |
| 298 | */ |
| 299 | const findByName = (accountId: string, name: string) => |
| 300 | zeroTrust.listDevicePostures.items({ accountId }).pipe( |
| 301 | Stream.filter((r) => r.name === name && r.id != null), |
| 302 | Stream.runCollect, |
| 303 | Effect.map((chunk) => |
| 304 | Array.from(chunk) |
| 305 | .sort((a, b) => (a.id ?? "").localeCompare(b.id ?? "")) |
| 306 | .at(0), |
| 307 | ), |
| 308 | ); |
| 309 | |
| 310 | const createRuleName = (id: string, name: string | undefined) => |
| 311 | Effect.gen(function* () { |
| 312 | return name ?? (yield* createPhysicalName({ id, lowercase: true })); |
| 313 | }); |
| 314 | |
| 315 | const toAttributes = (rule: ObservedRule, accountId: string): DevicePostureRuleAttributes => ({ |
| 316 | postureRuleId: rule.id ?? "", |
| 317 | accountId, |
| 318 | name: rule.name ?? "", |
| 319 | type: rule.type ?? "", |
| 320 | description: denull(rule.description), |
| 321 | schedule: denull(rule.schedule), |
| 322 | expiration: denull(rule.expiration), |
| 323 | match: normalizeMatch(rule.match), |
| 324 | input: denull(rule.input), |
| 325 | }); |
| 326 | |
| 327 | const normalizeMatch = ( |
| 328 | match: ObservedRule["match"], |
| 329 | ): { platform: string | undefined }[] | undefined => |
| 330 | match == null ? undefined : match.map((m) => ({ platform: denull(m.platform) })); |
| 331 | |
| 332 | /** |
| 333 | * Strip Cloudflare's `null` echoes to `undefined` so structural equality |
| 334 | * (`JSON.stringify`) works. |
| 335 | */ |
| 336 | const denull = <T>(v: T | null | undefined): T | undefined => (v == null ? undefined : v); |
| 337 | |
| 338 | /** Structural deep-equality via canonical JSON. */ |
| 339 | const sameJSON = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b); |