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

main
ts 564 lines 21.3 KB
Raw
1 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
2 import * as Provider from "alchemy/Provider";
3 import { Resource } from "alchemy/Resource";
4 import { stripNullFields, stripUndefinedFields } from "alchemy/Util/data";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
8 import type { Providers } from "../Providers.ts";
9
10 export type OrganizationProps = {
11 /**
12 * The unique subdomain assigned to your Zero Trust organization, e.g.
13 * `acme.cloudflareaccess.com`. Per-account this is functionally immutable —
14 * Cloudflare allocates exactly one team domain when the account first
15 * enables Zero Trust and changing it is a manual support operation.
16 *
17 * @see https://developers.cloudflare.com/cloudflare-one/setup/#1-create-a-team-name
18 */
19 authDomain: string;
20 /**
21 * Human-readable display name of your Zero Trust organization. Usually the
22 * same as `authDomain`. Mutable.
23 *
24 * @see https://developers.cloudflare.com/api/operations/zero-trust-organization-update-your-zero-trust-organization
25 */
26 name?: string;
27 /**
28 * Default session lifetime for Access applications. Must be a Go duration
29 * string (e.g. `30m`, `2h45m`, `24h`). Valid units: `ns`, `us`, `ms`, `s`,
30 * `m`, `h`. Per-application settings override this default.
31 *
32 * @see https://developers.cloudflare.com/cloudflare-one/identity/users/session-management/
33 */
34 sessionDuration?: string;
35 /**
36 * When `true`, users may authenticate to Access applications via the WARP
37 * client without going through the configured identity providers. Per-app
38 * settings take precedence.
39 *
40 * @default false
41 * @see https://developers.cloudflare.com/cloudflare-one/identity/devices/warp-authentication-identity/
42 */
43 allowAuthenticateViaWarp?: boolean;
44 /**
45 * When `true`, all Zero Trust settings in the Cloudflare dashboard are
46 * read-only and may only be modified via the API or Terraform.
47 *
48 * @default false
49 */
50 isUiReadOnly?: boolean;
51 /**
52 * When `true`, users skip the identity provider selection step on login.
53 * Only valid when exactly one IdP is configured (or one is set as default).
54 *
55 * @default false
56 */
57 autoRedirectToIdentity?: boolean;
58 /**
59 * Free-form description of why `isUiReadOnly` is toggled. Surfaced in the
60 * Cloudflare dashboard.
61 */
62 uiReadOnlyToggleReason?: string;
63 /**
64 * Duration of user-seat inactivity before the user is removed as an active
65 * seat and stops counting against the Teams seat quota. Go duration string.
66 */
67 userSeatExpirationInactiveTime?: string;
68 /**
69 * Lifetime of tokens issued by the WARP authentication flow. Go duration
70 * string limited to `m` and `h` units, e.g. `30m` or `2h45m`.
71 */
72 warpAuthSessionDuration?: string;
73 /**
74 * Branding for the Access login screen.
75 *
76 * @see https://developers.cloudflare.com/cloudflare-one/identity/users/login-page/
77 */
78 loginDesign?: Organization.LoginDesign;
79 /**
80 * Pointers to custom HTML pages shown when Access blocks a request.
81 *
82 * @see https://developers.cloudflare.com/cloudflare-one/policies/access/custom-pages/
83 */
84 customPages?: Organization.CustomPages;
85 /**
86 * When `true`, Access denies requests to hostnames on the account's zones
87 * that no Access application matches.
88 *
89 * @default false
90 * @see https://developers.cloudflare.com/cloudflare-one/access-controls/access-settings/require-access-protection/
91 */
92 denyUnmatchedRequests?: boolean;
93 /**
94 * Zones exempted from `denyUnmatchedRequests`, by zone name (e.g.
95 * `example.com`).
96 */
97 denyUnmatchedRequestsExemptedZoneNames?: string[];
98 /**
99 * When `true`, users can't create their own Access applications from the
100 * App Launcher.
101 *
102 * @default false
103 */
104 disableEndUserAppCreation?: boolean;
105 /**
106 * Organization-wide multi-factor authentication settings, applied to
107 * applications that require Access MFA.
108 *
109 * @see https://developers.cloudflare.com/cloudflare-one/access-controls/access-settings/independent-mfa/
110 */
111 mfaConfig?: Organization.MfaConfig;
112 /**
113 * Requirements for PIV keys and FIDO2 SSH keys used as MFA for
114 * infrastructure applications.
115 */
116 mfaPivKeyRequirements?: Organization.MfaPivKeyRequirements;
117 /**
118 * When `true`, every Access application requires MFA unless it opts out.
119 *
120 * @default false
121 */
122 mfaRequiredForAllApps?: boolean;
123 /**
124 * What happens to service tokens that go unused for a number of days.
125 */
126 serviceTokenInactivity?: Organization.ServiceTokenInactivity;
127 /**
128 * When `true`, a request that presents a service token is evaluated only
129 * against service-token policies.
130 *
131 * @default false
132 */
133 strictServiceTokenAuth?: boolean;
134 /**
135 * When `true`, WARP authentication answers non-browser requests that lack
136 * a session with `401` instead of redirecting to login.
137 *
138 * @default false
139 */
140 warpAuthNonBrowser401?: boolean;
141 };
142
143 export declare namespace Organization {
144 /**
145 * Branding for the Access login screen.
146 */
147 export interface LoginDesign {
148 /** URL of the logo image rendered at the top of the login form. */
149 logoPath?: string;
150 /** CSS color for the header background, e.g. `#1a1a1a`. */
151 headerBgColor?: string;
152 /** CSS color for the page background. */
153 backgroundColor?: string;
154 /** CSS color for the body text. */
155 textColor?: string;
156 /** Markdown rendered at the top of the login form (legacy). */
157 headerText?: string;
158 /** Markdown rendered at the bottom of the login form. */
159 footerText?: string;
160 }
161 /**
162 * Pointers to custom HTML pages shown when Access denies a request.
163 */
164 export interface CustomPages {
165 /**
166 * UUID of a custom forbidden page (created via the Access Custom Pages
167 * API) shown when a policy denies access.
168 */
169 forbidden?: string;
170 /**
171 * UUID of a custom identity-denied page shown when the identity provider
172 * rejects the user.
173 */
174 identityDenied?: string;
175 }
176 /**
177 * Organization-wide MFA settings.
178 */
179 export interface MfaConfig {
180 /**
181 * MFA methods users can authenticate with. `piv_key` and
182 * `ssh_fido2_key` apply only to infrastructure applications.
183 */
184 allowedAuthenticators?: (
185 | "totp"
186 | "biometrics"
187 | "security_key"
188 | "piv_key"
189 | "ssh_fido2_key"
190 )[];
191 /**
192 * How long a user may skip Access MFA when their identity provider
193 * already reports MFA in the `amr` claim, e.g. `12h`. Minutes or hours,
194 * `0m` to `720h`.
195 */
196 amrMatchingSessionDuration?: string;
197 /** ID of a Cloudflare List of allowed FIDO2 authenticator AAGUIDs. */
198 requiredAaguids?: string;
199 /** Lifetime of an MFA session, e.g. `24h`. Minutes or hours, `0m` to `720h`. */
200 sessionDuration?: string;
201 }
202 /**
203 * Requirements for PIV and SSH keys used as MFA.
204 */
205 export interface MfaPivKeyRequirements {
206 /** When a PIN is required to use the key. */
207 pinPolicy?: "never" | "once" | "always";
208 /** Require a FIPS 140-2 Level 1 (or higher) validated device. */
209 requireFipsDevice?: boolean;
210 /** Allowed SSH key sizes in bits. Ed25519 keys have a fixed size. */
211 sshKeySize?: (256 | 384 | 521 | 2048 | 3072 | 4096)[];
212 /** Allowed SSH key types. */
213 sshKeyType?: ("ecdsa" | "ed25519" | "rsa")[];
214 /** When a physical touch is required (`cached` lasts 15 seconds). */
215 touchPolicy?: "never" | "always" | "cached";
216 }
217 /**
218 * Automatic handling of inactive service tokens.
219 */
220 export interface ServiceTokenInactivity {
221 /** Whether inactive service tokens are acted on. */
222 enabled: boolean;
223 /** What to do with an inactive token. */
224 action: "disable" | "delete";
225 /** Days without use before a token counts as inactive. */
226 inactivityThresholdDays: number;
227 }
228 }
229
230 export type Organization = Resource<
231 "Cloudflare.Access.Organization",
232 OrganizationProps,
233 {
234 /** Cloudflare account that owns the Zero Trust organization. */
235 accountId: string;
236 /** The Zero Trust team domain, e.g. `acme.cloudflareaccess.com`. */
237 authDomain: string;
238 /** Display name of the organization. */
239 name: string;
240 /** Default Access application session duration. */
241 sessionDuration: string | undefined;
242 /** WARP-as-IdP toggle observed on Cloudflare. */
243 allowAuthenticateViaWarp: boolean | undefined;
244 /** Dashboard read-only lock observed on Cloudflare. */
245 isUiReadOnly: boolean | undefined;
246 /** Skip-IdP-picker toggle observed on Cloudflare. */
247 autoRedirectToIdentity: boolean | undefined;
248 /** Free-form note explaining the `isUiReadOnly` setting. */
249 uiReadOnlyToggleReason: string | undefined;
250 /** User-seat inactivity expiration observed on Cloudflare. */
251 userSeatExpirationInactiveTime: string | undefined;
252 /** WARP authentication session duration observed on Cloudflare. */
253 warpAuthSessionDuration: string | undefined;
254 /** Login-page branding observed on Cloudflare. */
255 loginDesign: Organization.LoginDesign | undefined;
256 /** Custom-pages pointers observed on Cloudflare. */
257 customPages: Organization.CustomPages | undefined;
258 /** Whether unmatched requests are denied. */
259 denyUnmatchedRequests: boolean | undefined;
260 /** Zones exempted from `denyUnmatchedRequests`. */
261 denyUnmatchedRequestsExemptedZoneNames: string[] | undefined;
262 /** Whether end users are blocked from creating applications. */
263 disableEndUserAppCreation: boolean | undefined;
264 /** Organization-wide MFA settings observed on Cloudflare. */
265 mfaConfig: Organization.MfaConfig | undefined;
266 /** PIV and SSH key requirements observed on Cloudflare. */
267 mfaPivKeyRequirements: Organization.MfaPivKeyRequirements | undefined;
268 /** Whether every application requires MFA. */
269 mfaRequiredForAllApps: boolean | undefined;
270 /** Inactive service token handling observed on Cloudflare. */
271 serviceTokenInactivity: Organization.ServiceTokenInactivity | undefined;
272 /** Whether service-token requests are evaluated only against service-token policies. */
273 strictServiceTokenAuth: boolean | undefined;
274 /** Whether WARP authentication answers non-browser requests with `401`. */
275 warpAuthNonBrowser401: boolean | undefined;
276 },
277 never,
278 Providers
279 >;
280
281 /**
282 * Account-level Cloudflare Zero Trust organization settings — the team
283 * domain, login branding, session lifetimes, MFA, WARP authentication, etc.
284 *
285 * Wraps `PUT /accounts/{account_id}/access/organizations`.
286 * @remarks
287 * **This resource is a singleton.** Every Cloudflare account owns exactly one
288 * Access Organization; you cannot create a second one and you cannot delete
289 * the existing one without deleting the entire Cloudflare account. As a
290 * result:
291 *
292 * - The `reconcile` lifecycle always **adopts** the existing organization on
293 * first deploy rather than failing on conflict.
294 * - The `delete` lifecycle is a **no-op** that logs a warning. Removing the
295 * resource from your stack leaves the Cloudflare-side settings untouched.
296 * - Every deploy converges the whole organization on the declared props. A
297 * setting you don't declare goes back to Cloudflare's default, including
298 * one changed in the dashboard — declare MFA, `denyUnmatchedRequests` and
299 * the rest here to keep them.
300 *
301 * ### Configuring the organization
302 * **Example:** Adopt and brand the organization
303 * ```typescript
304 * const org = yield* Cloudflare.Access.Organization("Org", {
305 * authDomain: "acme.cloudflareaccess.com",
306 * name: "Acme",
307 * sessionDuration: "24h",
308 * allowAuthenticateViaWarp: true,
309 * loginDesign: {
310 * logoPath: "https://acme.example/logo.png",
311 * backgroundColor: "#111111",
312 * textColor: "#ffffff",
313 * },
314 * });
315 * ```
316 *
317 * ### Branding the login page
318 * Keep the branding assets in your repo. An assets-only Worker serves the
319 * logo, and a custom page takes its HTML from a file.
320 *
321 * **Example:** Logo and block page from files
322 * ```typescript
323 * const fs = yield* FileSystem.FileSystem;
324 * const branding = yield* Cloudflare.Worker("Branding", {
325 * assets: "./branding/public", // logo.svg
326 * });
327 * const forbidden = yield* Cloudflare.Access.CustomPage("Forbidden", {
328 * type: "forbidden",
329 * customHtml: yield* fs.readFileString("./branding/forbidden.html"),
330 * });
331 * const org = yield* Cloudflare.Access.Organization("Org", {
332 * authDomain: "acme.cloudflareaccess.com",
333 * loginDesign: {
334 * logoPath: Output.interpolate`${branding.url}/logo.svg`,
335 * backgroundColor: "#111111",
336 * textColor: "#ffffff",
337 * footerText: "Acme employees only",
338 * },
339 * customPages: { forbidden: forbidden.customPageId },
340 * });
341 * ```
342 *
343 * ### Securing the organization
344 * **Example:** Require MFA and deny unmatched requests
345 * ```typescript
346 * const org = yield* Cloudflare.Access.Organization("Org", {
347 * authDomain: "acme.cloudflareaccess.com",
348 * mfaRequiredForAllApps: true,
349 * mfaConfig: {
350 * allowedAuthenticators: ["totp", "security_key"],
351 * sessionDuration: "12h",
352 * },
353 * denyUnmatchedRequests: true,
354 * denyUnmatchedRequestsExemptedZoneNames: ["public.example.com"],
355 * strictServiceTokenAuth: true,
356 * serviceTokenInactivity: {
357 * enabled: true,
358 * action: "disable",
359 * inactivityThresholdDays: 90,
360 * },
361 * });
362 * ```
363 *
364 * @resource
365 * @product Access
366 * @category Cloudflare One (Zero Trust)
367 */
368 export const Organization = Resource<Organization>("Cloudflare.Access.Organization", {
369 aliases: ["Cloudflare.AccessOrganization"],
370 });
371
372 /**
373 * Cloudflare returned `OrganizationAlreadyExists` on create, but the
374 * organization could not be read back afterwards.
375 */
376 export class OrganizationNotObserved extends Data.TaggedError("OrganizationNotObserved")<{
377 readonly accountId: string;
378 }> {}
379
380 export const OrganizationProvider = () =>
381 Provider.succeed(Organization, {
382 nuke: { singleton: true },
383 stables: ["accountId", "authDomain"],
384 reconcile: Effect.fn(function* ({ news }) {
385 const { accountId } = yield* yield* CloudflareEnvironment;
386
387 const desiredName = news.name ?? news.authDomain;
388 // The body is the complete desired state: every setting the props
389 // don't declare converges to its default.
390 // Observe — singleton lookup. The org always exists for any
391 // account that has enabled Zero Trust; only a brand-new account
392 // returns "missing".
393 const observed = yield* observe();
394 const settings = settingsBody(news, desiredName, observed);
395
396 // Ensure — create on a fresh account. If a race or out-of-band
397 // setup created it between the observe and create call, fall
398 // back to update.
399 if (!observed) {
400 const { customPages: _, ...createSettings } = settings;
401 yield* zeroTrust.createOrganizationForAccount({ accountId, ...createSettings }).pipe(
402 Effect.catchTag("OrganizationAlreadyExists", () =>
403 Effect.gen(function* () {
404 const existing = yield* observe();
405 if (existing) return existing;
406 return yield* new OrganizationNotObserved({ accountId });
407 }),
408 ),
409 );
410 }
411
412 // Sync — always push the full desired state so any drift converges
413 // in one call. Cheap and idempotent.
414 const updated = yield* zeroTrust.updateOrganizationForAccount({ accountId, ...settings });
415
416 return toAttrs(accountId, updated, news.authDomain, desiredName);
417 }),
418 delete: Effect.fn(function* () {
419 yield* Effect.logWarning(
420 "Organization.delete is a no-op — the Cloudflare Access Organization is a singleton tied to the account and cannot be deleted without deleting the Cloudflare account itself.",
421 );
422 }),
423 read: Effect.fn(function* ({ olds }) {
424 const { accountId } = yield* yield* CloudflareEnvironment;
425
426 const observed = yield* observe();
427 if (!observed) return undefined;
428 return toAttrs(
429 accountId,
430 observed,
431 olds?.authDomain ?? observed.authDomain ?? "",
432 olds?.name ?? observed.name ?? olds?.authDomain ?? "",
433 );
434 }),
435 // Account singleton: every Cloudflare account owns exactly one Access
436 // Organization and there is no enumeration API. Read the single org via
437 // the same `observe` path `read` uses and return the one-element array
438 // (or `[]` when the account has never enabled Zero Trust). `observe`
439 // already swallows the typed `OrganizationNotFound` error.
440 list: Effect.fn(function* () {
441 const { accountId } = yield* yield* CloudflareEnvironment;
442
443 const observed = yield* observe();
444 if (!observed) return [];
445 return [
446 toAttrs(
447 accountId,
448 observed,
449 observed.authDomain ?? "",
450 observed.name ?? observed.authDomain ?? "",
451 ),
452 ];
453 }),
454 });
455
456 const observe = Effect.fn(function* () {
457 const { accountId } = yield* yield* CloudflareEnvironment;
458
459 return yield* zeroTrust.listOrganizationsForAccount({ accountId }).pipe(
460 Effect.map((org) => {
461 // listOrganizationsForAccount returns a single object (the
462 // singleton org) under `result`; an account that has not yet
463 // enabled Zero Trust returns a sparse object with no
464 // `authDomain`. Treat that as "missing".
465 const typed = org;
466 return typed && typed.authDomain ? typed : undefined;
467 }),
468 Effect.catchTag("OrganizationNotFound", () => Effect.undefined),
469 );
470 });
471
472 /**
473 * The complete desired organization as an update body. Cloudflare resets
474 * most omitted settings but keeps some (`disableEndUserAppCreation`,
475 * `serviceTokenInactivity`), so undeclared toggles are sent as their
476 * defaults rather than left out.
477 */
478 const settingsBody = (
479 news: OrganizationProps,
480 name: string,
481 observed: zeroTrust.ListOrganizationsResponse | undefined,
482 ) =>
483 stripUndefinedFields({
484 authDomain: news.authDomain,
485 name,
486 sessionDuration: news.sessionDuration,
487 allowAuthenticateViaWarp: news.allowAuthenticateViaWarp ?? false,
488 isUiReadOnly: news.isUiReadOnly ?? false,
489 autoRedirectToIdentity: news.autoRedirectToIdentity ?? false,
490 uiReadOnlyToggleReason: news.uiReadOnlyToggleReason,
491 userSeatExpirationInactiveTime: news.userSeatExpirationInactiveTime,
492 warpAuthSessionDuration: news.warpAuthSessionDuration,
493 loginDesign: news.loginDesign,
494 customPages: news.customPages,
495 denyUnmatchedRequests: news.denyUnmatchedRequests ?? false,
496 denyUnmatchedRequestsExemptedZoneNames: news.denyUnmatchedRequestsExemptedZoneNames ?? [],
497 disableEndUserAppCreation: news.disableEndUserAppCreation ?? false,
498 mfaConfig: news.mfaConfig,
499 mfaPivKeyRequirements: news.mfaPivKeyRequirements,
500 mfaRequiredForAllApps: news.mfaRequiredForAllApps ?? false,
501 serviceTokenInactivity:
502 news.serviceTokenInactivity ??
503 disabledServiceTokenInactivity(observed?.serviceTokenInactivity),
504 strictServiceTokenAuth: news.strictServiceTokenAuth ?? false,
505 warp_auth_non_browser_401: news.warpAuthNonBrowser401 ?? false,
506 });
507
508 /**
509 * Turns off an enabled service-token inactivity policy the props don't
510 * declare. Cloudflare only accepts the full shape, so the observed action and
511 * threshold are sent back with `enabled: false`.
512 */
513 const disabledServiceTokenInactivity = (
514 observed: zeroTrust.ListOrganizationsResponse["serviceTokenInactivity"],
515 ): Organization.ServiceTokenInactivity | undefined =>
516 observed?.enabled && observed.action && observed.inactivityThresholdDays != null
517 ? {
518 enabled: false,
519 action: observed.action as Organization.ServiceTokenInactivity["action"],
520 inactivityThresholdDays: observed.inactivityThresholdDays,
521 }
522 : undefined;
523
524 /**
525 * Drops `null` fields from an observed nested setting, so the attribute has
526 * the same shape as the prop.
527 */
528 const observedSetting = <T>(value: object | null | undefined): T | undefined =>
529 value == null ? undefined : (stripNullFields(value) as T);
530
531 const toAttrs = (
532 accountId: string,
533 org: zeroTrust.ListOrganizationsResponse,
534 fallbackAuthDomain: string,
535 fallbackName: string,
536 ) => ({
537 accountId,
538 authDomain: org.authDomain ?? fallbackAuthDomain,
539 name: org.name ?? fallbackName,
540 sessionDuration: org.sessionDuration ?? undefined,
541 allowAuthenticateViaWarp: org.allowAuthenticateViaWarp ?? undefined,
542 isUiReadOnly: org.isUiReadOnly ?? undefined,
543 autoRedirectToIdentity: org.autoRedirectToIdentity ?? undefined,
544 uiReadOnlyToggleReason: org.uiReadOnlyToggleReason ?? undefined,
545 userSeatExpirationInactiveTime: org.userSeatExpirationInactiveTime ?? undefined,
546 warpAuthSessionDuration: org.warpAuthSessionDuration ?? undefined,
547 loginDesign: observedSetting<Organization.LoginDesign>(org.loginDesign),
548 customPages: observedSetting<Organization.CustomPages>(org.customPages),
549 denyUnmatchedRequests: org.denyUnmatchedRequests ?? undefined,
550 denyUnmatchedRequestsExemptedZoneNames: org.denyUnmatchedRequestsExemptedZoneNames
551 ? [...org.denyUnmatchedRequestsExemptedZoneNames]
552 : undefined,
553 disableEndUserAppCreation: org.disableEndUserAppCreation ?? undefined,
554 mfaConfig: observedSetting<Organization.MfaConfig>(org.mfaConfig),
555 mfaPivKeyRequirements: observedSetting<Organization.MfaPivKeyRequirements>(
556 org.mfaPivKeyRequirements,
557 ),
558 mfaRequiredForAllApps: org.mfaRequiredForAllApps ?? undefined,
559 serviceTokenInactivity: observedSetting<Organization.ServiceTokenInactivity>(
560 org.serviceTokenInactivity,
561 ),
562 strictServiceTokenAuth: org.strictServiceTokenAuth ?? undefined,
563 warpAuthNonBrowser401: org.warp_auth_non_browser_401 ?? undefined,
564 });