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

main
ts 1,622 lines 59 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 { isResourceOfType, Resource } from "alchemy/Resource";
6 import { arrayEquals, subsetDiffers } from "alchemy/Util/equal";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 normalizePolicyRules,
15 type PolicyDecision,
16 type PolicyExcludeRuleInput,
17 type PolicyRequireRuleInput,
18 type PolicyRuleInput,
19 } from "./Policy.ts";
20
21 export class ApplicationInvalidProps extends Data.TaggedError("ApplicationInvalidProps")<{
22 readonly message: string;
23 readonly cause?: unknown;
24 }> {}
25
26 export class ApplicationUnexpectedResponse extends Data.TaggedError(
27 "ApplicationUnexpectedResponse",
28 )<{
29 readonly message: string;
30 readonly cause?: unknown;
31 }> {}
32
33 /**
34 * Application type literal — every value Cloudflare's Access service
35 * recognises. Stable across reconciles; changing it triggers a replacement.
36 */
37 export type ApplicationType =
38 | "self_hosted"
39 | "saas"
40 | "ssh"
41 | "vnc"
42 | "bookmark"
43 | "warp"
44 | "infrastructure"
45 | "app_launcher"
46 | "biso"
47 | "dash_sso";
48
49 /**
50 * A destination that this Access application protects.
51 *
52 * Cloudflare supports these destination flavours:
53 * - `public` — a public hostname/URI you own in Cloudflare (the legacy
54 * `domain` field on `ApplicationProps` covers the simple case).
55 * - `private` — a hostname or CIDR reachable through a Cloudflare Tunnel.
56 * Traffic from WARP-enrolled devices is intercepted and forwarded
57 * through the tunnel; identity is enforced before forwarding.
58 * - `via_mcp_server_portal` — routes via a managed MCP server portal.
59 * - `worker` / `preview_worker` — a specific Cloudflare Worker's production
60 * traffic (custom domains, routes, `workers.dev`) or its version preview
61 * URLs, keyed by the Worker's immutable ID (its `workerId` attribute).
62 * Usually you don't write these by hand — set the `access` prop on the
63 * `Cloudflare.Worker` instead, and the Worker enrolls itself into the
64 * application.
65 * - `all_workers` / `all_preview_workers` — every Worker on the account
66 * (including ones created later), production or preview traffic
67 * respectively. Hostname-level policies take precedence over Worker-level
68 * policies, which take precedence over these account-level policies.
69 */
70 export type ApplicationDestination =
71 | { type: "public"; uri: string }
72 | {
73 type: "private";
74 hostname?: string;
75 cidr?: string;
76 l4Protocol?: "tcp" | "udp";
77 portRange?: string;
78 vnetId?: string;
79 }
80 | { type: "via_mcp_server_portal"; mcpServerId: string }
81 | { type: "worker"; workerId: string }
82 | { type: "preview_worker"; workerId: string }
83 | { type: "all_workers" }
84 | { type: "all_preview_workers" };
85
86 /**
87 * Configuration for an OAuth authorization flow managed by Cloudflare Access.
88 */
89 export interface OAuthConfiguration {
90 /** Whether Access acts as the OAuth authorization server. */
91 enabled?: boolean;
92 /** OAuth grant and token lifetimes. */
93 grant?: {
94 /** Lifetime of issued access tokens, as a Go-style duration. */
95 accessTokenLifetime?: string;
96 /** Lifetime of the authorization session, as a Go-style duration. */
97 sessionDuration?: string;
98 };
99 /** Settings for OAuth dynamic client registration. */
100 dynamicClientRegistration?: {
101 /** Whether dynamic client registration is enabled. */
102 enabled?: boolean;
103 /** Explicit redirect URIs that dynamically registered clients may use. */
104 allowedUris?: ReadonlyArray<string>;
105 /** Whether any localhost redirect URI is allowed. */
106 allowAnyOnLocalhost?: boolean;
107 /** Whether any loopback-address redirect URI is allowed. */
108 allowAnyOnLoopback?: boolean;
109 };
110 }
111
112 /**
113 * The `applicationId` declared on an {@link Application} does not exist in
114 * the account. Alchemy never creates an application in its place, so the
115 * declared id (and its `aud`) is never silently swapped for a new one.
116 */
117 export class DeclaredApplicationNotFound extends Data.TaggedError("DeclaredApplicationNotFound")<{
118 applicationId: string;
119 message: string;
120 }> {}
121
122 /** SAML or OIDC configuration of a `saas` application. */
123 export type SaasApp = zeroTrust.AccessApplicationsCreateRequestSaasApp;
124
125 /** CORS settings Access applies to requests to a self-hosted application. */
126 export type CorsHeaders = zeroTrust.AccessApplicationsCreateRequestCorsHeaders;
127
128 /**
129 * An Access policy defined inline on (and owned by) an application: created
130 * with the application, updated in place, and deleted with it. Uses the same
131 * rule model as the reusable `Cloudflare.Access.Policy` resource.
132 */
133 export interface InlineApplicationPolicy {
134 /** The action Access takes when a user matches this policy. */
135 decision: PolicyDecision;
136 /** Rules evaluated with OR — matching any one grants the policy. */
137 include: ReadonlyArray<PolicyRuleInput>;
138 /** Rules evaluated with NOT — matching any one denies the policy. */
139 exclude?: ReadonlyArray<PolicyExcludeRuleInput>;
140 /** Rules evaluated with AND — all must match. */
141 require?: ReadonlyArray<PolicyRequireRuleInput>;
142 /** Display name. Cloudflare generates one when omitted. */
143 name?: string;
144 /** Execution order of this policy within the application. */
145 precedence?: number;
146 /** Session lifetime for this policy, e.g. `"24h"`, `"2h45m"`. */
147 sessionDuration?: string;
148 /** Require admin approval at the start of each session. */
149 approvalRequired?: boolean;
150 /** Administrators who can approve a temporary authentication request. */
151 approvalGroups?: ReadonlyArray<{
152 approvalsNeeded: number;
153 emailAddresses?: ReadonlyArray<string>;
154 emailListUuid?: string;
155 }>;
156 /** Serve the application in an isolated browser for matching users. */
157 isolationRequired?: boolean;
158 /** Require a login justification from matching users. */
159 purposeJustificationRequired?: boolean;
160 /** Custom message shown on the justification screen. */
161 purposeJustificationPrompt?: string;
162 }
163
164 export interface ApplicationProps {
165 /**
166 * Cloudflare id of an existing application to manage. The first deploy
167 * takes that application over — keeping its `aud` — instead of creating a
168 * new one. The application must exist — a missing id fails the deploy
169 * with `DeclaredApplicationNotFound` instead of creating one. Changing
170 * the id replaces the resource.
171 */
172 applicationId?: string;
173 /**
174 * The Access application type.
175 *
176 * Cloudflare requires a single global `warp` application per account; the
177 * provider's observe step special-cases this by scanning the account for an
178 * existing `warp` app when no `applicationId` is cached.
179 *
180 * Immutable — changing the type triggers a replace.
181 */
182 type: ApplicationType;
183 /**
184 * Human-readable display name. If omitted, a deterministic physical name
185 * is generated from the app/stage/logical-id.
186 */
187 name?: string;
188 /**
189 * Primary hostname and path secured by Access. Required for `self_hosted`
190 * apps; ignored on the request for `warp` (Cloudflare auto-fills it with
191 * `${authDomain}/warp`) and `saas` (Cloudflare uses the OIDC issuer).
192 *
193 * Changing it without declaring `destinations` resets the application's
194 * hostnames to this domain.
195 */
196 domain?: string;
197 /**
198 * Destinations this application protects. Use for the modern multi-
199 * destination model — required for **Access for private apps** flows
200 * where traffic to a private hostname/CIDR is intercepted by WARP and
201 * routed through a Cloudflare Tunnel, with Access enforcing identity
202 * before the request reaches the upstream service.
203 *
204 * For simple public-hostname apps, set `domain` instead. The two are
205 * not mutually exclusive — Cloudflare treats `domain` as a shorthand
206 * for adding a single `{ type: "public" }` destination.
207 *
208 * @example
209 * ```ts
210 * destinations: [
211 * { type: "private", hostname: "admin.internal" },
212 * ]
213 * ```
214 */
215 destinations?: ReadonlyArray<ApplicationDestination>;
216 /**
217 * Optional OAuth authorization-server configuration managed by Access.
218 * Use this for non-browser clients such as MCP clients that authenticate
219 * through OAuth and may register redirect URIs dynamically.
220 */
221 oauthConfiguration?: OAuthConfiguration;
222 /**
223 * SAML or OIDC settings of a `saas` application. Merged over the live
224 * configuration, so values Cloudflare generates (`clientId`, `publicKey`,
225 * `ssoEndpoint`, `idpEntityId`) are kept.
226 */
227 saasApp?: SaasApp;
228 /**
229 * CORS settings for requests to the application. Cannot be combined with
230 * `optionsPreflightBypass`.
231 */
232 corsHeaders?: CorsHeaders;
233 /**
234 * Let `OPTIONS` preflight requests bypass Access and reach the origin.
235 * Cannot be combined with `corsHeaders`.
236 */
237 optionsPreflightBypass?: boolean;
238 /**
239 * `SameSite` attribute of the Access session cookie.
240 */
241 sameSiteCookieAttribute?: "strict" | "lax" | "none";
242 /**
243 * Set `HttpOnly` on the Access session cookie.
244 */
245 httpOnlyCookieAttribute?: boolean;
246 /**
247 * Enable the binding cookie, which protects against stolen authorization
248 * tokens and CSRF.
249 */
250 enableBindingCookie?: boolean;
251 /**
252 * Scope the Access JWT cookie to the application path instead of the
253 * hostname.
254 */
255 pathCookieAttribute?: boolean;
256 /**
257 * Preemptively set the Access session cookie on each concrete hostname
258 * of a multi-hostname self-hosted application during login. Set to false
259 * to issue cookies as each hostname is visited. Omit to preserve the live
260 * setting on updates or use Cloudflare's default for a new application.
261 * Wildcard hostnames cannot receive preemptive cookies.
262 */
263 eagerRedirectCookieSetting?: boolean;
264 /**
265 * Token TTL for sessions issued by this application. Accepts Go-style
266 * duration strings, e.g. `"24h"`, `"720h"`, `"2h45m"`.
267 *
268 * @default "24h"
269 */
270 sessionDuration?: string;
271 /**
272 * Allowed identity-provider UUIDs. Defaults (on Cloudflare's side) to every
273 * IdP configured for the account.
274 */
275 allowedIdps?: string[];
276 /**
277 * Skip the IdP picker when only one IdP is allowed. Requires `allowedIdps`
278 * to contain exactly one entry.
279 *
280 * @default false
281 */
282 autoRedirectToIdentity?: boolean;
283 /**
284 * Whether the app should be visible in the App Launcher dashboard.
285 */
286 appLauncherVisible?: boolean;
287 /**
288 * Tags applied to this application for filtering in the App Launcher.
289 */
290 tags?: string[];
291 /**
292 * Access policies that gate access to this application, in ascending
293 * order of precedence.
294 *
295 * Each entry can be:
296 * - an **inline policy** owned by this application —
297 * `{ decision, include, ... }` with the same rule model as
298 * `Cloudflare.Access.Policy` (created, updated, and deleted with the
299 * application; no separate resource needed),
300 * - a deployed reusable `Cloudflare.Access.Policy`
301 * (`policies: [allowTeam]`),
302 * - a policy id (`string`),
303 * - `{ id, precedence? }`, or
304 * - the same with per-application overrides (`approvalRequired`,
305 * `isolationRequired`, `purposeJustificationRequired`,
306 * `purposeJustificationPrompt`, `sessionDuration`, `approvalGroups`).
307 *
308 * Cloudflare treats inline and reusable policies as mutually exclusive on
309 * one application — mixing the two forms fails validation.
310 *
311 * If omitted, the application's live policies are left as they are. Pass
312 * `[]` to detach them.
313 *
314 * @example
315 * ```ts
316 * policies: [
317 * { decision: "allow", include: [{ emailDomain: "example.com" }] },
318 * ]
319 * ```
320 */
321 policies?: ReadonlyArray<
322 | string
323 | { policyId: string }
324 | InlineApplicationPolicy
325 | { id: string; precedence?: number }
326 | {
327 id: string;
328 precedence?: number;
329 approvalRequired?: boolean;
330 isolationRequired?: boolean;
331 purposeJustificationRequired?: boolean;
332 purposeJustificationPrompt?: string;
333 sessionDuration?: string;
334 approvalGroups?: ReadonlyArray<{
335 approvalsNeeded: number;
336 emailAddresses?: ReadonlyArray<string>;
337 emailListUuid?: string;
338 }>;
339 }
340 >;
341 /**
342 * Adopt an existing app that already lives in Cloudflare (matched by
343 * applicationId observation) instead of failing on conflict.
344 *
345 * @default false
346 */
347 adopt?: boolean;
348 }
349
350 /**
351 * Output attributes persisted between reconciles.
352 */
353 export interface ApplicationAttributes {
354 /** Cloudflare-assigned application UUID. */
355 applicationId: string;
356 /** Audience tag used to verify JWTs issued for this application. */
357 aud: string;
358 /** Resolved domain. Cloudflare fills this in for `warp`/`saas` apps. */
359 domain: string;
360 /** Resolved destinations (echoed back by Cloudflare). */
361 destinations: ReadonlyArray<ApplicationDestination> | undefined;
362 /** Resolved managed OAuth configuration. */
363 oauthConfiguration: OAuthConfiguration | undefined;
364 /**
365 * Resolved SaaS configuration, including the values Cloudflare generates
366 * (`clientId`, `publicKey`, `ssoEndpoint`, `idpEntityId`). The OIDC client
367 * secret is not stored.
368 */
369 saasApp: SaasApp | undefined;
370 /** Application type. */
371 type: ApplicationType;
372 /** Display name (resolved). */
373 name: string;
374 /** Account that owns this application. */
375 accountId: string;
376 /** ISO8601 creation timestamp (Cloudflare-supplied). */
377 createdAt: string | undefined;
378 /** ISO8601 last-update timestamp (Cloudflare-supplied). */
379 updatedAt: string | undefined;
380 }
381
382 /**
383 * Data other resources attach to an Access application via bindings.
384 * Workers enrolling themselves (the `access` prop on `Cloudflare.Worker`)
385 * push their `worker`/`preview_worker` destinations here; the application
386 * deploys with — and converges on — the union of its own `destinations`
387 * prop and every bound contribution.
388 */
389 export interface ApplicationBinding {
390 destinations?: ApplicationDestination[];
391 }
392
393 export const isApplication = <T>(value: T): value is T & Application =>
394 isResourceOfType(value, "Cloudflare.Access.Application");
395
396 export type Application = Resource<
397 "Cloudflare.Access.Application",
398 ApplicationProps,
399 ApplicationAttributes,
400 ApplicationBinding,
401 Providers
402 >;
403
404 /**
405 * A Cloudflare Zero Trust Access application.
406 *
407 * Replaces the curl-based `POST /accounts/{accountId}/access/apps` workflow
408 * with an Alchemy-managed resource. Supports every Cloudflare application
409 * type including `warp`, which Cloudflare requires for device enrolment via
410 * the WARP client.
411 *
412 * Settings left unset are not managed: updates keep their live values.
413 * ### Creating an Application
414 * **Example:** Self-hosted application gated by a reusable Access policy
415 * ```typescript
416 * const allowMyOrg = yield* Cloudflare.Access.Policy("AllowMyOrg", {
417 * name: "Allow example.com via Google",
418 * decision: "allow",
419 * include: [{ emailDomain: { domain: "example.com" } }],
420 * });
421 *
422 * const app = yield* Cloudflare.Access.Application("InternalDashboard", {
423 * type: "self_hosted",
424 * domain: "dashboard.example.com",
425 * sessionDuration: "24h",
426 * policies: [allowMyOrg],
427 * });
428 * ```
429 *
430 * **Example:** Managed OAuth for an MCP server
431 * ```typescript
432 * const app = yield* Cloudflare.Access.Application("McpServer", {
433 * type: "self_hosted",
434 * domain: "mcp.example.com",
435 * oauthConfiguration: {
436 * enabled: true,
437 * grant: {
438 * sessionDuration: "24h",
439 * accessTokenLifetime: "15m",
440 * },
441 * dynamicClientRegistration: {
442 * enabled: true,
443 * allowAnyOnLocalhost: true,
444 * allowAnyOnLoopback: true,
445 * },
446 * },
447 * });
448 * ```
449 *
450 * ### Adopting an existing application
451 * **Example:** Take over an application by its Cloudflare id
452 * ```typescript
453 * // Keeps the application's id and `aud`, so JWT validation keeps working.
454 * const app = yield* Cloudflare.Access.Application("Grafana", {
455 * applicationId: "4f8e3c1a-5b2d-4e6f-9a7b-1c2d3e4f5a6b",
456 * type: "self_hosted",
457 * domain: "grafana.example.com",
458 * sameSiteCookieAttribute: "lax",
459 * httpOnlyCookieAttribute: true,
460 * corsHeaders: {
461 * allowedOrigins: ["https://app.example.com"],
462 * allowedMethods: ["GET", "POST"],
463 * allowCredentials: true,
464 * },
465 * });
466 * ```
467 *
468 * ### SaaS applications
469 * **Example:** SAML application
470 * ```typescript
471 * const looker = yield* Cloudflare.Access.Application("Looker", {
472 * type: "saas",
473 * name: "Looker",
474 * saasApp: {
475 * authType: "saml",
476 * spEntityId: "https://example.looker.com",
477 * consumerServiceUrl: "https://example.looker.com/saml/acs",
478 * nameIdFormat: "email",
479 * },
480 * policies: [allowTeam],
481 * });
482 * // Configure the SaaS side with looker.saasApp.ssoEndpoint / publicKey.
483 * ```
484 *
485 * **Example:** OIDC application
486 * ```typescript
487 * const coder = yield* Cloudflare.Access.Application("Coder", {
488 * type: "saas",
489 * name: "Coder",
490 * saasApp: {
491 * authType: "oidc",
492 * redirectUris: ["https://coder.example.com/api/v2/users/oidc/callback"],
493 * grantTypes: ["authorization_code"],
494 * scopes: ["openid", "email", "profile"],
495 * },
496 * policies: [allowTeam],
497 * });
498 * ```
499 *
500 * ### Protecting Cloudflare Workers
501 * **Example:** Require Access on a specific Worker
502 * ```typescript
503 * // The application owns the policies (inline here — no separate Policy
504 * // resource needed); the Worker enrolls itself via its `access` prop,
505 * // covering its custom domains, routes, workers.dev URL, and version
506 * // preview URLs.
507 * const App = Cloudflare.Access.Application("TeamOnly", {
508 * type: "self_hosted",
509 * policies: [
510 * { decision: "allow", include: [{ emailDomain: "example.com" }] },
511 * ],
512 * });
513 *
514 * export default class Api extends Cloudflare.Worker<Api>()("Api", {
515 * main: import.meta.url,
516 * access: { application: App },
517 * }, /* ... *​/) {}
518 * ```
519 *
520 * **Example:** Require Access on every Worker in the account
521 * ```typescript
522 * // Covers all current AND future Workers. Hostname-level policies beat
523 * // Worker-level policies, which beat this account-level policy — so an
524 * // individual Worker can still be opened up with its own application.
525 * yield* Cloudflare.Access.Application("ProtectAllWorkers", {
526 * type: "self_hosted",
527 * destinations: [
528 * Cloudflare.Access.AllWorkers, // production traffic of every Worker
529 * Cloudflare.Access.AllWorkerPreviews, // every Worker's preview URLs
530 * ],
531 * policies: [
532 * { decision: "allow", include: [{ emailDomain: "example.com" }] },
533 * ],
534 * });
535 * ```
536 *
537 * ### Device-enrollment (warp)
538 * **Example:** WARP device-enrollment application
539 * ```typescript
540 * // There can only be ONE warp app per account; Cloudflare auto-derives the
541 * // domain (`${authDomain}/warp`) so do not pass `domain` for this type.
542 * const allowCorp = yield* Cloudflare.Access.Policy("AllowCorpUsers", {
543 * name: "Allow corp users",
544 * decision: "allow",
545 * include: [{ emailDomain: { domain: "example.com" } }],
546 * });
547 *
548 * const enroll = yield* Cloudflare.Access.Application("warp-login", {
549 * type: "warp",
550 * allowedIdps: [googleIdpId],
551 * autoRedirectToIdentity: true,
552 * sessionDuration: "720h",
553 * policies: [allowCorp],
554 * });
555 * ```
556 *
557 * ### Self-hosted with Google IdP
558 * **Example:** Self-hosted application restricted to a Google Workspace group
559 * ```typescript
560 * const admins = yield* Cloudflare.Access.Policy("AdminsOnly", {
561 * name: "Admins only",
562 * decision: "allow",
563 * include: [
564 * {
565 * gsuite: {
566 * email: "admins@example.com",
567 * identityProviderId: googleIdpUuid,
568 * },
569 * },
570 * ],
571 * });
572 *
573 * const app = yield* Cloudflare.Access.Application("AdminConsole", {
574 * type: "self_hosted",
575 * domain: "admin.example.com",
576 * allowedIdps: [googleIdpUuid],
577 * autoRedirectToIdentity: true,
578 * policies: [admins],
579 * });
580 * ```
581 *
582 * @resource
583 * @product Access
584 * @category Cloudflare One (Zero Trust)
585 */
586 export const Application = Resource<Application>("Cloudflare.Access.Application");
587
588 // Ride out the two transient failure modes Cloudflare's Access endpoints
589 // exhibit under load:
590 //
591 // - `AccessReferenceNotFound` (400 `policy <id> not found`): Access
592 // validates referenced entities (e.g. the `policies` an application gates
593 // on) synchronously, but a *freshly created* policy propagates
594 // eventually-consistently — so a create/update referencing it, or a list
595 // hydrating an app that references it, is briefly rejected. Distilled
596 // types this 400 distinctly (vs. a generic `BadRequest`) so we retry only
597 // this case and still fail fast on real bad requests.
598 // - `Forbidden` (403): Cloudflare frequently returns 403 when throttling a
599 // valid token rather than a dedicated rate-limit status, so a 403 here is
600 // a transient back-pressure signal, not an auth failure.
601 //
602 // Capped exponential, bounded to ride out the window (~45s) then fail.
603 const retryTransientAccessError = <A, E extends { _tag: string }, R>(
604 effect: Effect.Effect<A, E, R>,
605 ) =>
606 effect.pipe(
607 Effect.retry({
608 while: (e) => e._tag === "AccessReferenceNotFound" || e._tag === "Forbidden",
609 schedule: Schedule.max([
610 Schedule.min([Schedule.exponential("1 second", 1.5), Schedule.spaced("5 seconds")]),
611 Schedule.recurs(12),
612 ]),
613 }),
614 );
615
616 export const ApplicationProvider = () =>
617 Provider.succeed(Application, {
618 stables: ["applicationId", "aud", "type", "accountId"],
619
620 diff: Effect.fn(function* ({ olds = {}, news, output }) {
621 if ((olds as ApplicationProps).type !== undefined) {
622 if ((olds as ApplicationProps).type !== (news as ApplicationProps).type) {
623 return { action: "replace" } as const;
624 }
625 }
626 const declaredId = (news as ApplicationProps).applicationId;
627 if (
628 typeof declaredId === "string" &&
629 output !== undefined &&
630 declaredId !== output.applicationId
631 ) {
632 return { action: "replace" } as const;
633 }
634 }),
635
636 read: Effect.fn(function* ({ output, olds }) {
637 const { accountId } = yield* yield* CloudflareEnvironment;
638
639 // Prefer the persisted physical id. After state loss there is no
640 // applicationId to probe, so fall back to matching an existing app
641 // by domain — without this the engine plans a blind `create`, and
642 // Cloudflare happily creates a second application on the same
643 // domain with a fresh `aud`, silently breaking existing JWT
644 // validation. Warp apps are excluded from the fallback: they are a
645 // per-account singleton that `reconcile` already recovers.
646 const knownId = output?.applicationId ?? olds?.applicationId;
647 let observed: ObservedApp | undefined;
648 if (knownId) {
649 observed = yield* observeById(accountId, knownId);
650 } else if (olds?.type !== "warp" && typeof olds?.domain === "string") {
651 observed = yield* findByDomain(accountId, olds.domain);
652 } else {
653 return undefined;
654 }
655 if (!isComplete(observed)) {
656 return undefined;
657 }
658 const attrs = toAttributes(observed, output?.accountId ?? accountId, {
659 ...output,
660 domain: output?.domain ?? olds?.domain,
661 });
662 // Recovered by id → positively ours. Recovered by domain scan →
663 // existence is certain but ownership is not (Access applications
664 // carry no alchemy marker), so gate takeover behind `--adopt`.
665 return knownId ? attrs : Unowned(attrs);
666 }),
667
668 reconcile: Effect.fn(function* ({ id, news, output, bindings }) {
669 const { accountId } = yield* yield* CloudflareEnvironment;
670
671 const resolvedName = yield* resolveName(id, news.name);
672 const resolvedIdps = resolveAllowedIdps(news.allowedIdps);
673 const resolvedPolicies = resolvePolicies(news.policies);
674 if (
675 resolvedPolicies !== undefined &&
676 resolvedPolicies.some((p) => typeof p !== "string" && isInlinePolicy(p)) &&
677 resolvedPolicies.some((p) => typeof p === "string" || !isInlinePolicy(p))
678 ) {
679 return yield* new ApplicationInvalidProps({
680 message:
681 "Cloudflare Access applications cannot mix inline policies with " +
682 "reusable policy references — use one form for the whole " +
683 "`policies` list.",
684 });
685 }
686 const body = buildMutableBody(news, resolvedName, resolvedIdps, resolvedPolicies);
687 // Destinations contributed through the binding contract (e.g. Workers
688 // enrolling via their `access` prop) extend the declared ones. The
689 // engine dedupes and sid-sorts bindings, so the merged order is
690 // stable across deploys.
691 const boundDestinations = (bindings ?? []).flatMap(
692 (b) => (b.data.destinations ?? []) as ApplicationDestination[],
693 );
694 if (boundDestinations.length > 0) {
695 body.destinations = [...(body.destinations ?? []), ...boundDestinations];
696 }
697
698 // 1. Observe
699 const knownId = output?.applicationId ?? news.applicationId;
700 let observed: ObservedApp | undefined;
701 if (knownId) {
702 observed = yield* observeById(accountId, knownId);
703 }
704 if (!observed && news.applicationId !== undefined) {
705 return yield* new DeclaredApplicationNotFound({
706 applicationId: news.applicationId,
707 message: `Cloudflare Access application ${news.applicationId} does not exist`,
708 });
709 }
710 if (!observed && news.type === "warp") {
711 // Warp is a singleton per account — reuse any existing app.
712 observed = yield* findWarpApp(accountId);
713 }
714
715 // 2. Ensure
716 if (!observed) {
717 const created = yield* zeroTrust
718 .createAccessApplicationForAccount({
719 accountId,
720 domain: body.domain,
721 type: news.type,
722 name: resolvedName,
723 sessionDuration: body.sessionDuration,
724 allowedIdps: body.allowedIdps === undefined ? undefined : Array.from(body.allowedIdps),
725 autoRedirectToIdentity: body.autoRedirectToIdentity,
726 appLauncherVisible: body.appLauncherVisible,
727 tags: body.tags === undefined ? undefined : Array.from(body.tags),
728 policies: toRequestPolicies(body.policies),
729 destinations:
730 body.destinations === undefined ? undefined : Array.from(body.destinations),
731 oauthConfiguration: toRequestOAuthConfiguration(body.oauthConfiguration),
732 ...settingsOf(body),
733 })
734 .pipe(
735 // A referenced policy may be propagating, or the call may be
736 // throttled (403) — ride out both before falling through.
737 retryTransientAccessError,
738 // Distilled does not tag Conflict; surface any creation error
739 // through the warp-singleton recovery path before re-failing.
740 Effect.catch((err) =>
741 Effect.gen(function* () {
742 if (news.type === "warp") {
743 const existing = yield* findWarpApp(accountId);
744 if (existing) return existing;
745 }
746 return yield* err;
747 }),
748 ),
749 );
750 observed = narrowApp(created as Parameters<typeof narrowApp>[0]);
751 }
752
753 // 3. Sync — Cloudflare's update endpoint is PUT-style: anything missing
754 // from the body is reset. Start from the live application so settings
755 // this resource does not manage survive, then apply the desired body.
756 if (!observed.id) {
757 return yield* new ApplicationUnexpectedResponse({
758 message: "Cloudflare did not return an application id for Access application",
759 });
760 }
761 if (!bodyEqualsObserved(body, observed)) {
762 // Without desired destinations, keep every live hostname unless the
763 // primary domain changes (Cloudflare then resets to the new domain).
764 const destinations =
765 body.destinations ??
766 (body.domain === undefined || body.domain === observed.domain
767 ? observed.destinations
768 : undefined);
769 const updated = yield* zeroTrust
770 .updateAccessApplicationForAccount({
771 ...preservedSettings(observed),
772 accountId,
773 appId: observed.id,
774 domain: body.domain ?? observed.domain,
775 type: news.type,
776 name: resolvedName,
777 ...definedOnly({
778 sessionDuration: body.sessionDuration,
779 allowedIdps:
780 body.allowedIdps === undefined ? undefined : Array.from(body.allowedIdps),
781 autoRedirectToIdentity: body.autoRedirectToIdentity,
782 appLauncherVisible: body.appLauncherVisible,
783 tags: body.tags === undefined ? undefined : Array.from(body.tags),
784 policies: toRequestPolicies(
785 attachObservedPolicyIds(body.policies, observed.policies),
786 ),
787 destinations: destinations === undefined ? undefined : Array.from(destinations),
788 // Merge a partial managed OAuth configuration over the live one.
789 oauthConfiguration: toRequestOAuthConfiguration(
790 mergeOAuthConfiguration(observed.oauthConfiguration, body.oauthConfiguration),
791 ),
792 }),
793 ...mergeSettings(observed, settingsOf(body)),
794 })
795 // A just-added policy reference may still be propagating, or the
796 // call may be throttled (403) — ride out both.
797 .pipe(retryTransientAccessError);
798 observed = narrowApp(updated as Parameters<typeof narrowApp>[0]);
799 }
800
801 // 4. Return
802 if (!isComplete(observed)) {
803 return yield* new ApplicationUnexpectedResponse({
804 message: "Cloudflare returned an Access application without id/aud/type",
805 });
806 }
807 // Keep the provider output cloud-authoritative: if Cloudflare rejects
808 // or clears a desired setting, do not mask that drift with the body.
809 return toAttributes(observed, accountId, {
810 domain: body.domain,
811 destinations: body.destinations,
812 name: resolvedName,
813 });
814 }),
815
816 // Account-scoped collection (pattern (b)): enumerate every Access
817 // application in the ambient account, exhaustively paginated, and hydrate
818 // each into the exact `read`/`reconcile` Attributes shape. Items missing
819 // the mandatory id/aud/type triplet are skipped (typed per-item drop).
820 list: Effect.fn(function* () {
821 const { accountId } = yield* yield* CloudflareEnvironment;
822 return yield* zeroTrust.listAccessApplicationsForAccount.pages({ accountId }).pipe(
823 Stream.runCollect,
824 // The list hydrates each app's `policies`; Cloudflare rejects the
825 // whole enumeration with the typed `AccessReferenceNotFound` (400
826 // "policy ... not found") while a sibling app references a policy
827 // that is still propagating or mid-deletion, and 403s the call when
828 // throttling. Ride out both.
829 retryTransientAccessError,
830 Effect.map((chunk) =>
831 Array.from(chunk).flatMap((page) =>
832 (page.result ?? []).flatMap((raw) => {
833 const app = narrowApp(raw as Parameters<typeof narrowApp>[0]);
834 return isComplete(app) ? [toAttributes(app, accountId)] : [];
835 }),
836 ),
837 ),
838 );
839 }),
840
841 delete: Effect.fn(function* ({ output }) {
842 yield* zeroTrust
843 .deleteAccessApplicationForAccount({
844 accountId: output.accountId,
845 appId: output.applicationId,
846 })
847 .pipe(Effect.catch(() => Effect.void));
848 }),
849 });
850
851 const resolveName = (id: string, name: string | undefined) =>
852 Effect.gen(function* () {
853 if (name) return name;
854 return yield* createPhysicalName({ id });
855 });
856
857 const resolveAllowedIdps = (
858 idps: ApplicationProps["allowedIdps"],
859 ): ReadonlyArray<string> | undefined =>
860 idps === undefined
861 ? undefined
862 : // Inputs have already been resolved by the Plan layer by the time
863 // we run, so they're concrete strings here.
864 (idps as ReadonlyArray<string>);
865
866 // Cloudflare allows only one `warp` app per account. When we have no
867 // cached applicationId, scan the account and reuse it. Requirements
868 // (Credentials | HttpClient) are inferred and provided by the Provider
869 // runtime — matches the un-annotated Tunnel.findTunnelByName pattern.
870 const findWarpApp = (accountId: string) =>
871 zeroTrust.listAccessApplicationsForAccount.items({ accountId }).pipe(
872 Stream.runCollect,
873 // A sibling app mid-teardown can transiently reject the whole
874 // enumeration (AccessReferenceNotFound), and Cloudflare 403s when
875 // throttling — same transient windows `list` rides out.
876 retryTransientAccessError,
877 Effect.map((chunk) =>
878 Array.from(chunk).find((a) => (a as { type?: string | null }).type === "warp"),
879 ),
880 Effect.map((found) =>
881 found === undefined ? undefined : narrowApp(found as Parameters<typeof narrowApp>[0]),
882 ),
883 );
884
885 // Cold-recovery scan for `read` when no applicationId was persisted:
886 // match an existing application by its domain (unique per account for
887 // non-warp app types).
888 const findByDomain = (accountId: string, domain: string) =>
889 zeroTrust.listAccessApplicationsForAccount.items({ accountId }).pipe(
890 Stream.runCollect,
891 // A sibling app mid-teardown can transiently reject the whole
892 // enumeration (AccessReferenceNotFound), and Cloudflare 403s when
893 // throttling. A missed scan here is worse than a slow one: the engine
894 // would plan a blind `create` and either duplicate the app or trip
895 // Cloudflare's `application_already_exists` Conflict.
896 retryTransientAccessError,
897 Effect.map((chunk) =>
898 Array.from(chunk).find((a) => (a as { domain?: string | null }).domain === domain),
899 ),
900 Effect.map((found) =>
901 found === undefined ? undefined : narrowApp(found as Parameters<typeof narrowApp>[0]),
902 ),
903 );
904
905 const observeById = (accountId: string, appId: string) =>
906 Effect.gen(function* () {
907 const r = yield* zeroTrust.getAccessApplicationForAccount({ accountId, appId }).pipe(
908 // A missing application is typed (404 → AccessApplicationNotFound):
909 // observe falls through to recreate. Transient 403 back-pressure is
910 // retried; anything else is a real failure and propagates.
911 retryTransientAccessError,
912 Effect.catchTag("AccessApplicationNotFound", () => Effect.undefined),
913 );
914 if (r === undefined) return undefined;
915 return narrowApp(r as Parameters<typeof narrowApp>[0]);
916 });
917
918 // ---------------------------------------------------------------------------
919 // Observed-state types
920 //
921 // We only diff policy references by id (and order), so the observed policy
922 // shape is narrowed to just the identifier here.
923 // ---------------------------------------------------------------------------
924
925 interface ObservedPolicy {
926 readonly id?: string;
927 readonly precedence?: number;
928 /** false for application-owned (inline) policies, true for reusable. */
929 readonly reusable?: boolean;
930 readonly decision?: string;
931 readonly name?: string;
932 readonly include?: ReadonlyArray<unknown>;
933 readonly exclude?: ReadonlyArray<unknown>;
934 readonly require?: ReadonlyArray<unknown>;
935 readonly sessionDuration?: string;
936 readonly approvalRequired?: boolean;
937 readonly isolationRequired?: boolean;
938 readonly purposeJustificationRequired?: boolean;
939 readonly purposeJustificationPrompt?: string;
940 }
941
942 interface ObservedApp {
943 /** The decoded response, for carrying unmanaged settings through updates. */
944 readonly raw: Readonly<Record<string, unknown>>;
945 readonly id?: string;
946 readonly aud?: string;
947 readonly name?: string;
948 readonly type?: ApplicationType;
949 readonly domain?: string;
950 readonly destinations?: ReadonlyArray<ApplicationDestination>;
951 readonly oauthConfiguration?: OAuthConfiguration;
952 readonly saasApp?: SaasApp;
953 readonly allowedIdps?: ReadonlyArray<string>;
954 readonly autoRedirectToIdentity?: boolean;
955 readonly appLauncherVisible?: boolean;
956 readonly sessionDuration?: string;
957 readonly tags?: ReadonlyArray<string>;
958 readonly policies?: ReadonlyArray<ObservedPolicy>;
959 readonly createdAt?: string;
960 readonly updatedAt?: string;
961 }
962
963 const isComplete = (
964 app: ObservedApp | undefined,
965 ): app is ObservedApp & { id: string; aud: string; type: ApplicationType } =>
966 !!app?.id && !!app.aud && !!app.type;
967
968 const toAttributes = (
969 app: ObservedApp & { id: string; aud: string; type: ApplicationType },
970 accountId: string,
971 fallback?: Partial<ApplicationAttributes>,
972 ): ApplicationAttributes => ({
973 applicationId: app.id,
974 aud: app.aud,
975 // SaaS and Worker-destination apps have no hostname; Cloudflare omits
976 // `domain` for them entirely.
977 domain: app.domain ?? fallback?.domain ?? "",
978 destinations: app.destinations ?? fallback?.destinations,
979 // Live cloud state is authoritative. In particular, do not resurrect
980 // a persisted configuration when Cloudflare explicitly returns null.
981 oauthConfiguration: app.oauthConfiguration,
982 saasApp: app.saasApp,
983 type: app.type,
984 name: app.name ?? fallback?.name ?? "",
985 accountId,
986 createdAt: app.createdAt ?? fallback?.createdAt,
987 updatedAt: app.updatedAt ?? fallback?.updatedAt,
988 });
989
990 const undef = <T>(v: T | null | undefined): T | undefined => (v == null ? undefined : v);
991
992 const undefArr = <T>(
993 v: ReadonlyArray<T | null> | null | undefined,
994 ): ReadonlyArray<T> | undefined =>
995 v == null ? undefined : (v.filter((x) => x != null) as ReadonlyArray<T>);
996
997 interface RawOAuthConfiguration {
998 readonly enabled?: boolean | null;
999 readonly grant?: {
1000 readonly accessTokenLifetime?: string | null;
1001 readonly sessionDuration?: string | null;
1002 } | null;
1003 readonly dynamicClientRegistration?: {
1004 readonly enabled?: boolean | null;
1005 readonly allowedUris?: ReadonlyArray<string | null> | null;
1006 readonly allowAnyOnLocalhost?: boolean | null;
1007 readonly allowAnyOnLoopback?: boolean | null;
1008 } | null;
1009 }
1010
1011 const narrowOAuthConfiguration = (
1012 raw: RawOAuthConfiguration | null | undefined,
1013 ): OAuthConfiguration | undefined =>
1014 raw == null
1015 ? undefined
1016 : {
1017 enabled: undef(raw.enabled),
1018 grant:
1019 raw.grant == null
1020 ? undefined
1021 : {
1022 accessTokenLifetime: undef(raw.grant.accessTokenLifetime),
1023 sessionDuration: undef(raw.grant.sessionDuration),
1024 },
1025 dynamicClientRegistration:
1026 raw.dynamicClientRegistration == null
1027 ? undefined
1028 : {
1029 enabled: undef(raw.dynamicClientRegistration.enabled),
1030 allowedUris: undefArr(raw.dynamicClientRegistration.allowedUris) as
1031 | string[]
1032 | undefined,
1033 allowAnyOnLocalhost: undef(raw.dynamicClientRegistration.allowAnyOnLocalhost),
1034 allowAnyOnLoopback: undef(raw.dynamicClientRegistration.allowAnyOnLoopback),
1035 },
1036 };
1037
1038 const narrowApp = (raw: {
1039 id?: string | null;
1040 aud?: string | null;
1041 name?: string | null;
1042 type?: string | null;
1043 domain?: string | null;
1044 destinations?: ReadonlyArray<unknown> | null;
1045 oauthConfiguration?: RawOAuthConfiguration | null;
1046 saasApp?: object | null;
1047 allowedIdps?: ReadonlyArray<string> | null;
1048 autoRedirectToIdentity?: boolean | null;
1049 appLauncherVisible?: boolean | null;
1050 sessionDuration?: string | null;
1051 tags?: ReadonlyArray<string> | null;
1052 policies?: ReadonlyArray<unknown> | null;
1053 createdAt?: string | null;
1054 updatedAt?: string | null;
1055 }): ObservedApp => ({
1056 raw,
1057 id: undef(raw.id),
1058 aud: undef(raw.aud),
1059 name: undef(raw.name),
1060 type: raw.type == null ? undefined : (raw.type as ApplicationType),
1061 domain: undef(raw.domain),
1062 destinations:
1063 raw.destinations == null
1064 ? undefined
1065 : (raw.destinations as ReadonlyArray<ApplicationDestination>),
1066 oauthConfiguration: narrowOAuthConfiguration(raw.oauthConfiguration),
1067 saasApp:
1068 raw.saasApp == null
1069 ? undefined
1070 : (withoutNulls(omit(raw.saasApp, ["clientSecret", "createdAt", "updatedAt"])) as SaasApp),
1071 allowedIdps: undefArr(raw.allowedIdps ?? undefined),
1072 autoRedirectToIdentity: undef(raw.autoRedirectToIdentity),
1073 appLauncherVisible: undef(raw.appLauncherVisible),
1074 sessionDuration: undef(raw.sessionDuration),
1075 tags: undefArr(raw.tags ?? undefined),
1076 policies: raw.policies == null ? undefined : (raw.policies as ReadonlyArray<ObservedPolicy>),
1077 createdAt: undef(raw.createdAt),
1078 updatedAt: undef(raw.updatedAt),
1079 });
1080
1081 // ---------------------------------------------------------------------------
1082 // Body construction
1083 //
1084 // Inputs declared as `Input<string>` are concrete strings by the time the
1085 // reconciler runs (resolved by the Plan layer). We narrow them at the
1086 // resolution boundary, then build the request shape distilled already types
1087 // correctly — no cast-to-Parameters needed.
1088 // ---------------------------------------------------------------------------
1089
1090 /**
1091 * Reconciler-side inline policy: `InlineApplicationPolicy` plus the optional
1092 * `id` of the observed application-owned policy it updates in place (see
1093 * `attachObservedPolicyIds`).
1094 */
1095 interface InlineResolvedPolicy extends InlineApplicationPolicy {
1096 id?: string;
1097 }
1098
1099 const isInlinePolicy = (p: ResolvedPolicy): p is InlineResolvedPolicy =>
1100 typeof p !== "string" && "decision" in p;
1101
1102 type ResolvedPolicy =
1103 | string
1104 | InlineResolvedPolicy
1105 | { id: string; precedence?: number }
1106 | {
1107 id: string;
1108 precedence?: number;
1109 approvalRequired?: boolean;
1110 isolationRequired?: boolean;
1111 purposeJustificationRequired?: boolean;
1112 purposeJustificationPrompt?: string;
1113 sessionDuration?: string;
1114 approvalGroups?: ReadonlyArray<{
1115 approvalsNeeded: number;
1116 emailAddresses?: ReadonlyArray<string>;
1117 emailListUuid?: string;
1118 }>;
1119 };
1120
1121 // The self-hosted policies item union: references (id string / link /
1122 // per-app overrides) plus application-owned inline policies
1123 // (`InlineAccessPolicy`, added to distilled's model — the API docs only
1124 // carry the inline arm for infrastructure apps, but the live API accepts
1125 // it for self_hosted).
1126 type RequestPolicy =
1127 zeroTrust.AccessApplicationsCreateForAccountRequestPoliciesSelfHostedApplicationItem;
1128
1129 // Settings sent verbatim when set and diffed against the live application.
1130 const SETTINGS = [
1131 "saasApp",
1132 "corsHeaders",
1133 "optionsPreflightBypass",
1134 "sameSiteCookieAttribute",
1135 "httpOnlyCookieAttribute",
1136 "enableBindingCookie",
1137 "pathCookieAttribute",
1138 "eagerRedirectCookieSetting",
1139 ] as const satisfies ReadonlyArray<keyof ApplicationProps>;
1140
1141 type Settings = Pick<ApplicationProps, (typeof SETTINGS)[number]>;
1142
1143 const settingsOf = (props: Settings): Settings =>
1144 Object.fromEntries(
1145 SETTINGS.flatMap((key) => (props[key] === undefined ? [] : [[key, props[key]]])),
1146 );
1147
1148 // Object settings merge over the live value: Cloudflare-generated SaaS
1149 // values (`clientId`, `publicKey`, ...) must be sent back to be kept.
1150 const mergeSettings = (observed: ObservedApp, desired: Settings): Settings =>
1151 Object.fromEntries(
1152 Object.entries(desired).map(([key, value]) => {
1153 const live = key === "saasApp" ? observed.saasApp : withoutNulls(observed.raw[key]);
1154 return [key, isRecord(value) && isRecord(live) ? { ...live, ...value } : value];
1155 }),
1156 );
1157
1158 // Everything a PUT would otherwise reset, taken from the live application.
1159 // Identity, policies, destinations and OAuth are reconciled explicitly; SCIM
1160 // config is left out because Cloudflare does not echo its credentials.
1161 const preservedSettings = (observed: ObservedApp) => ({
1162 ...(withoutNulls(
1163 omit(observed.raw, [
1164 "id",
1165 "aud",
1166 "type",
1167 "name",
1168 "domain",
1169 "createdAt",
1170 "updatedAt",
1171 "policies",
1172 "destinations",
1173 "selfHostedDomains",
1174 "oauthConfiguration",
1175 "scimConfig",
1176 "saasApp",
1177 ]),
1178 ) as Omit<zeroTrust.UpdateAccessApplicationForAccountRequest, "accountId" | "appId">),
1179 ...(observed.saasApp === undefined ? {} : { saasApp: observed.saasApp }),
1180 });
1181
1182 const isRecord = (value: unknown): value is Record<string, unknown> =>
1183 typeof value === "object" && value !== null && !Array.isArray(value);
1184
1185 const omit = (value: object, keys: ReadonlyArray<string>) =>
1186 Object.fromEntries(Object.entries(value).filter(([key]) => !keys.includes(key)));
1187
1188 const definedOnly = <T extends object>(value: T): Partial<T> =>
1189 Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined)) as Partial<T>;
1190
1191 const withoutNulls = (value: unknown): unknown =>
1192 Array.isArray(value)
1193 ? value.filter((v) => v != null).map(withoutNulls)
1194 : isRecord(value)
1195 ? Object.fromEntries(
1196 Object.entries(value)
1197 .filter(([, v]) => v != null)
1198 .map(([k, v]) => [k, withoutNulls(v)]),
1199 )
1200 : value;
1201
1202 interface AppMutableBody extends Settings {
1203 domain?: string;
1204 destinations?: ReadonlyArray<ApplicationDestination>;
1205 oauthConfiguration?: OAuthConfiguration;
1206 type: ApplicationType;
1207 name?: string;
1208 sessionDuration?: string;
1209 allowedIdps?: ReadonlyArray<string>;
1210 autoRedirectToIdentity?: boolean;
1211 appLauncherVisible?: boolean;
1212 tags?: ReadonlyArray<string>;
1213 policies?: ReadonlyArray<ResolvedPolicy>;
1214 }
1215
1216 const policyIdOf = (p: ResolvedPolicy): string | undefined => (typeof p === "string" ? p : p.id);
1217
1218 const toRequestPolicy = (p: ResolvedPolicy): RequestPolicy => {
1219 if (typeof p === "string") return p;
1220 if (isInlinePolicy(p)) {
1221 return {
1222 // `id` present when this inline body updates an observed
1223 // application-owned policy in place (attachObservedPolicyIds).
1224 id: p.id,
1225 decision: p.decision,
1226 include: normalizePolicyRules(p.include) as zeroTrust.InlineAccessPolicy["include"],
1227 exclude: normalizePolicyRules(p.exclude) as zeroTrust.InlineAccessPolicy["exclude"],
1228 require: normalizePolicyRules(p.require) as zeroTrust.InlineAccessPolicy["require"],
1229 name: p.name,
1230 precedence: p.precedence,
1231 sessionDuration: p.sessionDuration,
1232 approvalRequired: p.approvalRequired,
1233 approvalGroups:
1234 p.approvalGroups === undefined
1235 ? undefined
1236 : p.approvalGroups.map((g) => ({
1237 approvalsNeeded: g.approvalsNeeded,
1238 emailAddresses:
1239 g.emailAddresses === undefined ? undefined : Array.from(g.emailAddresses),
1240 emailListUuid: g.emailListUuid,
1241 })),
1242 isolationRequired: p.isolationRequired,
1243 purposeJustificationRequired: p.purposeJustificationRequired,
1244 purposeJustificationPrompt: p.purposeJustificationPrompt,
1245 } satisfies zeroTrust.InlineAccessPolicy;
1246 }
1247 // The simple `{ id, precedence? }` form lacks the per-app override fields;
1248 // narrow once to a permissive view so we can copy them through uniformly.
1249 const rich = p as {
1250 id: string;
1251 precedence?: number;
1252 approvalRequired?: boolean;
1253 isolationRequired?: boolean;
1254 purposeJustificationRequired?: boolean;
1255 purposeJustificationPrompt?: string;
1256 sessionDuration?: string;
1257 approvalGroups?: ReadonlyArray<{
1258 approvalsNeeded: number;
1259 emailAddresses?: ReadonlyArray<string>;
1260 emailListUuid?: string;
1261 }>;
1262 };
1263 return {
1264 id: rich.id,
1265 precedence: rich.precedence,
1266 approvalRequired: rich.approvalRequired,
1267 isolationRequired: rich.isolationRequired,
1268 purposeJustificationRequired: rich.purposeJustificationRequired,
1269 purposeJustificationPrompt: rich.purposeJustificationPrompt,
1270 sessionDuration: rich.sessionDuration,
1271 approvalGroups:
1272 rich.approvalGroups === undefined
1273 ? undefined
1274 : rich.approvalGroups.map((g) => ({
1275 approvalsNeeded: g.approvalsNeeded,
1276 emailAddresses:
1277 g.emailAddresses === undefined ? undefined : Array.from(g.emailAddresses),
1278 emailListUuid: g.emailListUuid,
1279 })),
1280 };
1281 };
1282
1283 const toRequestPolicies = (
1284 policies: ReadonlyArray<ResolvedPolicy> | undefined,
1285 ): Array<RequestPolicy> | undefined =>
1286 policies === undefined ? undefined : policies.map(toRequestPolicy);
1287
1288 const mergeOAuthConfiguration = (
1289 observed: OAuthConfiguration | undefined,
1290 desired: OAuthConfiguration | undefined,
1291 ): OAuthConfiguration | undefined => {
1292 if (desired === undefined) return observed;
1293 return {
1294 enabled: desired.enabled ?? observed?.enabled,
1295 grant:
1296 desired.grant === undefined
1297 ? observed?.grant
1298 : {
1299 accessTokenLifetime:
1300 desired.grant.accessTokenLifetime ?? observed?.grant?.accessTokenLifetime,
1301 sessionDuration: desired.grant.sessionDuration ?? observed?.grant?.sessionDuration,
1302 },
1303 dynamicClientRegistration:
1304 desired.dynamicClientRegistration === undefined
1305 ? observed?.dynamicClientRegistration
1306 : {
1307 enabled:
1308 desired.dynamicClientRegistration.enabled ??
1309 observed?.dynamicClientRegistration?.enabled,
1310 allowedUris:
1311 desired.dynamicClientRegistration.allowedUris ??
1312 observed?.dynamicClientRegistration?.allowedUris,
1313 allowAnyOnLocalhost:
1314 desired.dynamicClientRegistration.allowAnyOnLocalhost ??
1315 observed?.dynamicClientRegistration?.allowAnyOnLocalhost,
1316 allowAnyOnLoopback:
1317 desired.dynamicClientRegistration.allowAnyOnLoopback ??
1318 observed?.dynamicClientRegistration?.allowAnyOnLoopback,
1319 },
1320 };
1321 };
1322
1323 const toRequestOAuthConfiguration = (
1324 config: OAuthConfiguration | undefined,
1325 ): zeroTrust.CreateAccessApplicationForAccountRequest["oauthConfiguration"] =>
1326 config === undefined
1327 ? undefined
1328 : {
1329 enabled: config.enabled,
1330 grant: config.grant,
1331 dynamicClientRegistration:
1332 config.dynamicClientRegistration === undefined
1333 ? undefined
1334 : {
1335 ...config.dynamicClientRegistration,
1336 allowedUris:
1337 config.dynamicClientRegistration.allowedUris === undefined
1338 ? undefined
1339 : Array.from(config.dynamicClientRegistration.allowedUris),
1340 },
1341 };
1342
1343 const resolvePolicies = (
1344 policies: ApplicationProps["policies"],
1345 ): ReadonlyArray<ResolvedPolicy> | undefined =>
1346 policies === undefined
1347 ? undefined
1348 : // Inputs are concrete values here — the Plan layer resolved them
1349 // before the reconciler ran. A whole `Access.Policy` resource resolves
1350 // to its Attributes; normalize it to the bare policy id so everything
1351 // downstream (diffing, request building) sees one shape.
1352 (policies as ReadonlyArray<ResolvedPolicy | { policyId: string }>).map((p) =>
1353 typeof p !== "string" && "policyId" in p ? p.policyId : p,
1354 );
1355
1356 const buildMutableBody = (
1357 news: ApplicationProps,
1358 resolvedName: string,
1359 resolvedAllowedIdps: ReadonlyArray<string> | undefined,
1360 resolvedPolicies: ReadonlyArray<ResolvedPolicy> | undefined,
1361 ): AppMutableBody => {
1362 const body: AppMutableBody = {
1363 ...settingsOf(news),
1364 type: news.type,
1365 name: resolvedName,
1366 };
1367 // Warp apps cannot accept a user-supplied domain — Cloudflare derives it.
1368 if (news.type !== "warp" && news.domain !== undefined) {
1369 body.domain = news.domain;
1370 }
1371 if (news.destinations !== undefined) {
1372 body.destinations = news.destinations;
1373 }
1374 if (news.oauthConfiguration !== undefined) {
1375 body.oauthConfiguration = news.oauthConfiguration;
1376 }
1377 if (news.sessionDuration !== undefined) {
1378 body.sessionDuration = news.sessionDuration;
1379 }
1380 if (resolvedAllowedIdps !== undefined) {
1381 body.allowedIdps = resolvedAllowedIdps;
1382 }
1383 if (news.autoRedirectToIdentity !== undefined) {
1384 body.autoRedirectToIdentity = news.autoRedirectToIdentity;
1385 }
1386 if (news.appLauncherVisible !== undefined) {
1387 body.appLauncherVisible = news.appLauncherVisible;
1388 }
1389 if (news.tags !== undefined) {
1390 body.tags = news.tags;
1391 }
1392 if (resolvedPolicies !== undefined) {
1393 body.policies = resolvedPolicies;
1394 }
1395 return body;
1396 };
1397
1398 // ---------------------------------------------------------------------------
1399 // Drift detection
1400 // ---------------------------------------------------------------------------
1401
1402 const jsonEq = <T>(x: T, y: T): boolean => JSON.stringify(x) === JSON.stringify(y);
1403
1404 const oauthConfigurationEquals = (
1405 desired: OAuthConfiguration | undefined,
1406 observed: OAuthConfiguration | undefined,
1407 ): boolean => {
1408 if (desired === undefined) return true;
1409 if (observed === undefined) return false;
1410 if (desired.enabled !== undefined && desired.enabled !== observed.enabled) {
1411 return false;
1412 }
1413
1414 const desiredGrant = desired.grant;
1415 if (desiredGrant?.accessTokenLifetime !== undefined) {
1416 if (desiredGrant.accessTokenLifetime !== observed.grant?.accessTokenLifetime) {
1417 return false;
1418 }
1419 }
1420 if (desiredGrant?.sessionDuration !== undefined) {
1421 if (desiredGrant.sessionDuration !== observed.grant?.sessionDuration) {
1422 return false;
1423 }
1424 }
1425
1426 const desiredRegistration = desired.dynamicClientRegistration;
1427 const observedRegistration = observed.dynamicClientRegistration;
1428 if (
1429 desiredRegistration?.enabled !== undefined &&
1430 desiredRegistration.enabled !== observedRegistration?.enabled
1431 ) {
1432 return false;
1433 }
1434 if (
1435 desiredRegistration?.allowAnyOnLocalhost !== undefined &&
1436 desiredRegistration.allowAnyOnLocalhost !== observedRegistration?.allowAnyOnLocalhost
1437 ) {
1438 return false;
1439 }
1440 if (
1441 desiredRegistration?.allowAnyOnLoopback !== undefined &&
1442 desiredRegistration.allowAnyOnLoopback !== observedRegistration?.allowAnyOnLoopback
1443 ) {
1444 return false;
1445 }
1446 if (
1447 desiredRegistration?.allowedUris !== undefined &&
1448 !arrayEquals(
1449 [...desiredRegistration.allowedUris].sort(),
1450 [...(observedRegistration?.allowedUris ?? [])].sort(),
1451 jsonEq,
1452 )
1453 ) {
1454 return false;
1455 }
1456 return true;
1457 };
1458
1459 const policiesEq = (
1460 desired: ReadonlyArray<ResolvedPolicy> | undefined,
1461 observed: ReadonlyArray<ObservedPolicy> | undefined,
1462 ): boolean => {
1463 // Omitted `policies` leaves the live links unmanaged; an explicit `[]`
1464 // detaches them.
1465 if (desired === undefined) return true;
1466 if (observed === undefined) return desired.length === 0;
1467 if (desired.length !== observed.length) return false;
1468 for (let i = 0; i < desired.length; i++) {
1469 const d = desired[i];
1470 const o = observed[i];
1471 if (typeof d !== "string" && isInlinePolicy(d)) {
1472 // Inline (application-owned) policy: compare the fields the caller
1473 // set against the observed policy body. Cloudflare echoes rule
1474 // objects structurally, so JSON equality is stable; getting this
1475 // wrong is costly — a false inequality re-PUTs the policy list and
1476 // id-less inline items would mint fresh policies every deploy.
1477 if (o.reusable === true) return false;
1478 if (d.decision !== o.decision) return false;
1479 // Compare in wire shape: the caller may have used the scalar
1480 // shorthand while Cloudflare echoes expanded rules.
1481 const include = normalizePolicyRules(d.include);
1482 if (!jsonEq(include, (o.include ?? []) as typeof include)) {
1483 return false;
1484 }
1485 const exclude = normalizePolicyRules(d.exclude);
1486 if (exclude !== undefined && !jsonEq(exclude, (o.exclude ?? []) as typeof exclude)) {
1487 return false;
1488 }
1489 const require = normalizePolicyRules(d.require);
1490 if (require !== undefined && !jsonEq(require, (o.require ?? []) as typeof require)) {
1491 return false;
1492 }
1493 if (d.name !== undefined && d.name !== o.name) return false;
1494 if (
1495 d.precedence !== undefined &&
1496 o.precedence !== undefined &&
1497 d.precedence !== o.precedence
1498 ) {
1499 return false;
1500 }
1501 if (d.sessionDuration !== undefined && d.sessionDuration !== o.sessionDuration) {
1502 return false;
1503 }
1504 if (
1505 d.approvalRequired !== undefined &&
1506 d.approvalRequired !== (o.approvalRequired ?? false)
1507 ) {
1508 return false;
1509 }
1510 if (
1511 d.isolationRequired !== undefined &&
1512 d.isolationRequired !== (o.isolationRequired ?? false)
1513 ) {
1514 return false;
1515 }
1516 if (
1517 d.purposeJustificationRequired !== undefined &&
1518 d.purposeJustificationRequired !== (o.purposeJustificationRequired ?? false)
1519 ) {
1520 return false;
1521 }
1522 continue;
1523 }
1524 // Reference forms: an observed application-owned policy can never
1525 // satisfy a reusable reference.
1526 if (o.reusable === false) return false;
1527 if (policyIdOf(d) !== o.id) return false;
1528 if (typeof d !== "string") {
1529 if (
1530 d.precedence !== undefined &&
1531 o.precedence !== undefined &&
1532 d.precedence !== o.precedence
1533 ) {
1534 return false;
1535 }
1536 }
1537 }
1538 return true;
1539 };
1540
1541 /**
1542 * Zip desired inline policies with the observed application-owned policies
1543 * so an update PUT carries their ids and updates them in place — an id-less
1544 * inline item in an update creates a brand-new policy (and drops the old
1545 * one), churning policy ids on every deploy that touches any app field.
1546 * Positional matching, guarded on `reusable === false` (never attach a
1547 * reusable policy's id to an inline body — that would mutate the shared
1548 * policy) and on a matching decision.
1549 */
1550 const attachObservedPolicyIds = (
1551 desired: ReadonlyArray<ResolvedPolicy> | undefined,
1552 observed: ReadonlyArray<ObservedPolicy> | undefined,
1553 ): ReadonlyArray<ResolvedPolicy> | undefined =>
1554 desired === undefined || observed === undefined
1555 ? desired
1556 : desired.map((p, i) => {
1557 const o = observed[i];
1558 return typeof p !== "string" &&
1559 isInlinePolicy(p) &&
1560 p.id === undefined &&
1561 o?.id !== undefined &&
1562 o.reusable === false &&
1563 o.decision === p.decision
1564 ? { ...p, id: o.id }
1565 : p;
1566 });
1567
1568 const bodyEqualsObserved = (desired: AppMutableBody, observed: ObservedApp): boolean => {
1569 if (desired.name !== undefined && desired.name !== observed.name) {
1570 return false;
1571 }
1572 // Only diff domain when caller actually set one (warp's auto-derived
1573 // domain must not trigger a perpetual update loop).
1574 if (desired.domain !== undefined && desired.domain !== observed.domain) {
1575 return false;
1576 }
1577 // Same rule for destinations — Cloudflare may echo back an enriched
1578 // shape (e.g. server-assigned `vnetId`); we only diff when the caller
1579 // explicitly set them.
1580 if (
1581 desired.destinations !== undefined &&
1582 JSON.stringify(desired.destinations) !== JSON.stringify(observed.destinations ?? [])
1583 ) {
1584 return false;
1585 }
1586 if (!oauthConfigurationEquals(desired.oauthConfiguration, observed.oauthConfiguration)) {
1587 return false;
1588 }
1589 if (
1590 desired.sessionDuration !== undefined &&
1591 desired.sessionDuration !== observed.sessionDuration
1592 ) {
1593 return false;
1594 }
1595 if (
1596 desired.autoRedirectToIdentity !== undefined &&
1597 desired.autoRedirectToIdentity !== observed.autoRedirectToIdentity
1598 ) {
1599 return false;
1600 }
1601 if (
1602 desired.appLauncherVisible !== undefined &&
1603 desired.appLauncherVisible !== observed.appLauncherVisible
1604 ) {
1605 return false;
1606 }
1607 if (
1608 desired.allowedIdps !== undefined &&
1609 !arrayEquals(desired.allowedIdps, observed.allowedIdps, jsonEq)
1610 ) {
1611 return false;
1612 }
1613 if (desired.tags !== undefined && !arrayEquals(desired.tags, observed.tags, jsonEq)) {
1614 return false;
1615 }
1616 if (!policiesEq(desired.policies, observed.policies)) {
1617 return false;
1618 }
1619 return SETTINGS.every(
1620 (key) => !subsetDiffers(desired[key], key === "saasApp" ? observed.saasApp : observed.raw[key]),
1621 );
1622 };