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 Redacted from "effect/Redacted"; |
| 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.Devices.PostureIntegration" as const; |
| 15 | type TypeId = typeof TypeId; |
| 16 | |
| 17 | /** |
| 18 | * The third-party provider behind the posture integration. Determines |
| 19 | * which {@link DevicePostureIntegrationConfig} fields are required. |
| 20 | */ |
| 21 | export type DevicePostureIntegrationType = |
| 22 | | "workspace_one" |
| 23 | | "crowdstrike_s2s" |
| 24 | | "uptycs" |
| 25 | | "intune" |
| 26 | | "kolide" |
| 27 | | "tanium_s2s" |
| 28 | | "sentinelone_s2s" |
| 29 | | "custom_s2s"; |
| 30 | |
| 31 | /** |
| 32 | * Connection settings for the third-party posture provider. Which fields |
| 33 | * are required depends on the integration `type`: |
| 34 | * |
| 35 | * - `workspace_one` — `apiUrl`, `authUrl`, `clientId`, `clientSecret` |
| 36 | * - `crowdstrike_s2s` — `apiUrl`, `clientId`, `clientSecret`, `customerId` |
| 37 | * - `uptycs` — `apiUrl`, `clientKey`, `clientSecret`, `customerId` |
| 38 | * - `intune` — `clientId`, `clientSecret`, `customerId` |
| 39 | * - `kolide` — `clientId`, `clientSecret` |
| 40 | * - `tanium_s2s` — `apiUrl`, `clientSecret`, optional `accessClientId` / |
| 41 | * `accessClientSecret` |
| 42 | * - `sentinelone_s2s` — `apiUrl`, `clientSecret` |
| 43 | * - `custom_s2s` — `apiUrl`, `clientSecret`, `accessClientId`, |
| 44 | * `accessClientSecret` |
| 45 | * |
| 46 | * Secrets are write-only: Cloudflare never returns them on reads, so they |
| 47 | * are carried forward from the desired state. |
| 48 | */ |
| 49 | export interface DevicePostureIntegrationConfig { |
| 50 | /** The third-party API URL the integration polls. */ |
| 51 | apiUrl?: string; |
| 52 | /** The OAuth authorization URL (workspace_one). */ |
| 53 | authUrl?: string; |
| 54 | /** The OAuth client ID used to authenticate with the provider. */ |
| 55 | clientId?: string; |
| 56 | /** The client key (uptycs). */ |
| 57 | clientKey?: string; |
| 58 | /** The customer/tenant identifier (crowdstrike, uptycs, intune). */ |
| 59 | customerId?: string; |
| 60 | /** The OAuth client secret. Write-only — never returned on reads. */ |
| 61 | clientSecret?: Redacted.Redacted<string>; |
| 62 | /** Access service-token client ID guarding the custom endpoint. */ |
| 63 | accessClientId?: string; |
| 64 | /** Access service-token client secret. Write-only. */ |
| 65 | accessClientSecret?: Redacted.Redacted<string>; |
| 66 | } |
| 67 | |
| 68 | export interface DevicePostureIntegrationProps { |
| 69 | /** |
| 70 | * Name of the posture integration. If omitted, a unique name is |
| 71 | * generated from the app, stage, and logical ID. |
| 72 | * @default ${app}-${stage}-${id} |
| 73 | */ |
| 74 | name?: string; |
| 75 | /** |
| 76 | * The third-party provider type. Immutable — changing it triggers a |
| 77 | * replacement. |
| 78 | */ |
| 79 | type: DevicePostureIntegrationType; |
| 80 | /** |
| 81 | * The interval between each posture check against the third-party API. |
| 82 | * Use `m` for minutes (e.g. `5m`) and `h` for hours (e.g. `12h`). |
| 83 | */ |
| 84 | interval: string; |
| 85 | /** |
| 86 | * Connection settings for the provider (see |
| 87 | * {@link DevicePostureIntegrationConfig} for the per-type field |
| 88 | * requirements). Cloudflare validates the credentials against the live |
| 89 | * third-party API on create/update. |
| 90 | */ |
| 91 | config: DevicePostureIntegrationConfig; |
| 92 | } |
| 93 | |
| 94 | export type DevicePostureIntegrationAttributes = { |
| 95 | /** API UUID of the posture integration. */ |
| 96 | integrationId: string; |
| 97 | /** Account that owns the integration. */ |
| 98 | accountId: string; |
| 99 | /** Observed integration name. */ |
| 100 | name: string; |
| 101 | /** The third-party provider type. */ |
| 102 | type: DevicePostureIntegrationType; |
| 103 | /** Observed polling interval. */ |
| 104 | interval: string; |
| 105 | /** Non-secret connection details as reported by Cloudflare. */ |
| 106 | config: { |
| 107 | apiUrl: string | undefined; |
| 108 | authUrl: string | undefined; |
| 109 | clientId: string | undefined; |
| 110 | }; |
| 111 | }; |
| 112 | |
| 113 | export type DevicePostureIntegration = Resource< |
| 114 | TypeId, |
| 115 | DevicePostureIntegrationProps, |
| 116 | DevicePostureIntegrationAttributes, |
| 117 | never, |
| 118 | Providers |
| 119 | >; |
| 120 | |
| 121 | /** |
| 122 | * A Cloudflare Zero Trust **device posture integration** — a service-to- |
| 123 | * service connection to a third-party endpoint security provider |
| 124 | * (CrowdStrike, Intune, Kolide, Workspace ONE, ...) whose signals power |
| 125 | * `*_s2s` device posture rules. |
| 126 | * |
| 127 | * Cloudflare validates the configured credentials against the live |
| 128 | * provider API at create/update time, so a reachable third-party tenant |
| 129 | * is required. |
| 130 | * ### Creating a posture integration |
| 131 | * **Example:** CrowdStrike Falcon |
| 132 | * ```typescript |
| 133 | * const falcon = yield* Cloudflare.Devices.DevicePostureIntegration("Falcon", { |
| 134 | * type: "crowdstrike_s2s", |
| 135 | * interval: "10m", |
| 136 | * config: { |
| 137 | * apiUrl: "https://api.crowdstrike.com", |
| 138 | * clientId: Alchemy.env("CROWDSTRIKE_CLIENT_ID"), |
| 139 | * clientSecret: Redacted.make(process.env.CROWDSTRIKE_SECRET!), |
| 140 | * customerId: "ccid-1234", |
| 141 | * }, |
| 142 | * }); |
| 143 | * ``` |
| 144 | * |
| 145 | * **Example:** Custom service-to-service provider behind Access |
| 146 | * ```typescript |
| 147 | * const custom = yield* Cloudflare.Devices.DevicePostureIntegration("Custom", { |
| 148 | * type: "custom_s2s", |
| 149 | * interval: "30m", |
| 150 | * config: { |
| 151 | * apiUrl: "https://posture.example.com/check", |
| 152 | * clientSecret: Redacted.make(process.env.POSTURE_SECRET!), |
| 153 | * accessClientId: serviceToken.clientId, |
| 154 | * accessClientSecret: serviceToken.clientSecret, |
| 155 | * }, |
| 156 | * }); |
| 157 | * ``` |
| 158 | * |
| 159 | * **Example:** Reference the integration from a posture rule |
| 160 | * ```typescript |
| 161 | * yield* Cloudflare.Devices.DevicePostureRule("FalconScore", { |
| 162 | * type: "crowdstrike_s2s", |
| 163 | * input: { connectionId: falcon.integrationId, os: "windows" }, |
| 164 | * }); |
| 165 | * ``` |
| 166 | * |
| 167 | * @see https://developers.cloudflare.com/cloudflare-one/identity/devices/service-providers/ |
| 168 | * |
| 169 | * @resource |
| 170 | * @product Devices |
| 171 | * @category Cloudflare One (Zero Trust) |
| 172 | */ |
| 173 | export const DevicePostureIntegration = Resource<DevicePostureIntegration>(TypeId); |
| 174 | |
| 175 | /** |
| 176 | * Returns true if the given value is a DevicePostureIntegration resource. |
| 177 | */ |
| 178 | export const isDevicePostureIntegration = (value: unknown): value is DevicePostureIntegration => |
| 179 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 180 | |
| 181 | export const DevicePostureIntegrationProvider = () => |
| 182 | Provider.succeed(DevicePostureIntegration, { |
| 183 | stables: ["integrationId", "accountId", "type"], |
| 184 | |
| 185 | // Account collection — enumerate every posture integration in the |
| 186 | // ambient account, exhaustively paginating the distilled list op. |
| 187 | // Zero Trust is plan-gated; a `Forbidden` rejection means the account |
| 188 | // lacks the entitlement, so treat it as "nothing to list". |
| 189 | list: Effect.fn(function* () { |
| 190 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 191 | return yield* zeroTrust.listDevicePostureIntegrations.pages({ accountId }).pipe( |
| 192 | Stream.runCollect, |
| 193 | Effect.map((chunk) => |
| 194 | Array.from(chunk).flatMap((page) => |
| 195 | (page.result ?? []).map((i) => toAttributes(i, accountId)), |
| 196 | ), |
| 197 | ), |
| 198 | Effect.catchTag("Forbidden", () => Effect.succeed([])), |
| 199 | ); |
| 200 | }), |
| 201 | |
| 202 | diff: Effect.fn(function* ({ olds, news, output }) { |
| 203 | if (!isResolved(news)) return undefined; |
| 204 | // The provider type is immutable on Cloudflare's side — the config |
| 205 | // shapes are disjoint, so model a type change as replacement. |
| 206 | const oldType = output?.type ?? olds?.type; |
| 207 | if (oldType !== undefined && oldType !== news.type) { |
| 208 | return { action: "replace" } as const; |
| 209 | } |
| 210 | return undefined; |
| 211 | }), |
| 212 | |
| 213 | read: Effect.fn(function* ({ id, output, olds }) { |
| 214 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 215 | const acct = output?.accountId ?? accountId; |
| 216 | |
| 217 | if (output?.integrationId) { |
| 218 | const observed = yield* observeIntegration(acct, output.integrationId); |
| 219 | return observed ? toAttributes(observed, acct) : undefined; |
| 220 | } |
| 221 | |
| 222 | // Cold lookup by deterministic name. The list result carries no |
| 223 | // ownership markers, so brand the match `Unowned` and let the |
| 224 | // engine gate takeover behind the adopt policy. |
| 225 | const name = yield* createIntegrationName(id, olds?.name); |
| 226 | const match = yield* findByName(acct, name); |
| 227 | if (match) return Unowned(toAttributes(match, acct)); |
| 228 | return undefined; |
| 229 | }), |
| 230 | |
| 231 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 232 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 233 | const name = yield* createIntegrationName(id, news.name); |
| 234 | |
| 235 | // 1. Observe — `output.integrationId` is a cached hint; fall back to |
| 236 | // a name scan so a crashed prior run converges. |
| 237 | let observed = output?.integrationId |
| 238 | ? yield* observeIntegration(accountId, output.integrationId) |
| 239 | : undefined; |
| 240 | if (!observed) { |
| 241 | observed = yield* findByName(accountId, name); |
| 242 | } |
| 243 | |
| 244 | // 2. Ensure — create when missing. |
| 245 | if (!observed) { |
| 246 | const created = yield* zeroTrust.createDevicePostureIntegration({ |
| 247 | accountId, |
| 248 | name, |
| 249 | type: news.type, |
| 250 | interval: news.interval, |
| 251 | config: encodeConfig(news.config), |
| 252 | }); |
| 253 | return toAttributes(created, accountId); |
| 254 | } |
| 255 | |
| 256 | // 3. Sync — secrets are masked on reads so they cannot be diffed |
| 257 | // against observed state; PATCH when any observable field drifts |
| 258 | // OR when the desired config carries secrets that may have |
| 259 | // rotated. Cloudflare re-validates credentials on PATCH, so only |
| 260 | // send config when the non-secret surface differs. |
| 261 | const sameObservable = |
| 262 | (observed.name ?? "") === name && |
| 263 | (observed.interval ?? "") === news.interval && |
| 264 | sameObservedConfig(observed.config, news.config); |
| 265 | if (sameObservable) { |
| 266 | return toAttributes(observed, accountId); |
| 267 | } |
| 268 | const updated = yield* zeroTrust.patchDevicePostureIntegration({ |
| 269 | accountId, |
| 270 | integrationId: observed.id!, |
| 271 | name, |
| 272 | type: news.type, |
| 273 | interval: news.interval, |
| 274 | config: encodeConfig(news.config), |
| 275 | }); |
| 276 | return toAttributes(updated, accountId); |
| 277 | }), |
| 278 | |
| 279 | delete: Effect.fn(function* ({ output }) { |
| 280 | yield* zeroTrust |
| 281 | .deleteDevicePostureIntegration({ |
| 282 | accountId: output.accountId, |
| 283 | integrationId: output.integrationId, |
| 284 | }) |
| 285 | .pipe(Effect.catchTag("DevicePostureIntegrationNotFound", () => Effect.void)); |
| 286 | }), |
| 287 | }); |
| 288 | |
| 289 | /** |
| 290 | * Structural shape shared by get/list/create/patch responses. |
| 291 | */ |
| 292 | type ObservedIntegration = { |
| 293 | id?: string | null; |
| 294 | config?: { apiUrl: string; authUrl: string; clientId: string } | null; |
| 295 | interval?: string | null; |
| 296 | name?: string | null; |
| 297 | type?: (string & {}) | null; |
| 298 | }; |
| 299 | |
| 300 | /** |
| 301 | * Read an integration by id, mapping "gone" to `undefined`. |
| 302 | */ |
| 303 | const observeIntegration = (accountId: string, integrationId: string) => |
| 304 | zeroTrust |
| 305 | .getDevicePostureIntegration({ accountId, integrationId }) |
| 306 | .pipe(Effect.catchTag("DevicePostureIntegrationNotFound", () => Effect.undefined)); |
| 307 | |
| 308 | /** |
| 309 | * Find an integration by exact name. |
| 310 | */ |
| 311 | const findByName = (accountId: string, name: string) => |
| 312 | zeroTrust |
| 313 | .listDevicePostureIntegrations({ accountId }) |
| 314 | .pipe(Effect.map((list) => list.result.find((i) => i.name === name && i.id != null))); |
| 315 | |
| 316 | const createIntegrationName = (id: string, name: string | undefined) => |
| 317 | Effect.gen(function* () { |
| 318 | return name ?? (yield* createPhysicalName({ id, lowercase: true })); |
| 319 | }); |
| 320 | |
| 321 | type EncodedConfig = Parameters<typeof zeroTrust.createDevicePostureIntegration>[0]["config"]; |
| 322 | |
| 323 | /** |
| 324 | * Project the alchemy config (flat, secrets `Redacted`) onto the wire |
| 325 | * shape. The distilled request type is a union of per-provider structs; |
| 326 | * the API discriminates by the sibling `type` field, so a single |
| 327 | * present-fields projection is sufficient. The localized cast bridges the |
| 328 | * flat shape to the union — it never touches error handling. |
| 329 | */ |
| 330 | const encodeConfig = (config: DevicePostureIntegrationConfig): EncodedConfig => { |
| 331 | const out: Record<string, string> = {}; |
| 332 | if (config.apiUrl !== undefined) out.apiUrl = config.apiUrl; |
| 333 | if (config.authUrl !== undefined) out.authUrl = config.authUrl; |
| 334 | if (config.clientId !== undefined) out.clientId = config.clientId; |
| 335 | if (config.clientKey !== undefined) out.clientKey = config.clientKey; |
| 336 | if (config.customerId !== undefined) out.customerId = config.customerId; |
| 337 | if (config.clientSecret !== undefined) { |
| 338 | out.clientSecret = Redacted.value(config.clientSecret); |
| 339 | } |
| 340 | if (config.accessClientId !== undefined) { |
| 341 | out.accessClientId = config.accessClientId; |
| 342 | } |
| 343 | if (config.accessClientSecret !== undefined) { |
| 344 | out.accessClientSecret = Redacted.value(config.accessClientSecret); |
| 345 | } |
| 346 | return out as EncodedConfig; |
| 347 | }; |
| 348 | |
| 349 | /** |
| 350 | * Compare only the fields Cloudflare echoes back (secrets are masked). |
| 351 | */ |
| 352 | const sameObservedConfig = ( |
| 353 | observed: ObservedIntegration["config"], |
| 354 | desired: DevicePostureIntegrationConfig, |
| 355 | ): boolean => |
| 356 | observed != null && |
| 357 | (desired.apiUrl === undefined || observed.apiUrl === desired.apiUrl) && |
| 358 | (desired.authUrl === undefined || observed.authUrl === desired.authUrl) && |
| 359 | (desired.clientId === undefined || observed.clientId === desired.clientId); |
| 360 | |
| 361 | const toAttributes = ( |
| 362 | integration: ObservedIntegration, |
| 363 | accountId: string, |
| 364 | ): DevicePostureIntegrationAttributes => ({ |
| 365 | integrationId: integration.id ?? "", |
| 366 | accountId, |
| 367 | name: integration.name ?? "", |
| 368 | type: (integration.type ?? "custom_s2s") as DevicePostureIntegrationType, |
| 369 | interval: integration.interval ?? "", |
| 370 | config: { |
| 371 | apiUrl: integration.config?.apiUrl ?? undefined, |
| 372 | authUrl: integration.config?.authUrl ?? undefined, |
| 373 | clientId: integration.config?.clientId ?? undefined, |
| 374 | }, |
| 375 | }); |