@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 581 lines 19.8 KB
Raw
1 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { stripNullFields } from "alchemy/Util/data";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Option from "effect/Option";
10 import * as Stream from "effect/Stream";
11 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
12 import type { Providers } from "../Providers.ts";
13
14 export class PolicyUnexpectedResponse extends Data.TaggedError("PolicyUnexpectedResponse")<{
15 readonly message: string;
16 readonly cause?: unknown;
17 }> {}
18
19 /**
20 * One arm of a Cloudflare Access policy rule discriminated union. A rule is a
21 * single-key object whose key selects the rule kind (`email`, `emailDomain`,
22 * `everyone`, `ip`, etc.) and whose value carries the rule's parameters.
23 *
24 * Re-exported from `@distilled.cloud/cloudflare/zero-trust`'s
25 * `CreateAccessPolicyRequest` so the full Cloudflare rule surface is available
26 * without re-declaring the union.
27 */
28 export type PolicyRule = zeroTrust.CreateAccessPolicyRequest["include"][number];
29
30 /**
31 * One arm of the exclude-side rule union, and its require-side twin.
32 * Cloudflare's spec types the exclude/require rule lists separately from
33 * include — a few rule kinds (e.g. the GitHub-organization rule) carry the
34 * raw wire shape there — so these props use the SDK's own unions rather
35 * than reusing {@link PolicyRule}.
36 */
37 export type PolicyExcludeRule = NonNullable<zeroTrust.CreateAccessPolicyRequest["exclude"]>[number];
38 export type PolicyRequireRule = NonNullable<zeroTrust.CreateAccessPolicyRequest["require"]>[number];
39
40 /**
41 * Scalar shorthand for rule kinds with a single parameter (and bare names
42 * for the parameter-less kinds) — expanded to Cloudflare's wire shape by
43 * the providers, so both spellings are equivalent:
44 *
45 * ```ts
46 * include: [{ emailDomain: "example.com" }] // { emailDomain: { domain: "example.com" } }
47 * include: [{ email: "sam@example.com" }] // { email: { email: "sam@example.com" } }
48 * include: ["everyone"] // { everyone: {} }
49 * require: [{ geo: "US" }] // { geo: { countryCode: "US" } }
50 * ```
51 *
52 * Multi-parameter kinds (`gsuite`, `okta`, `saml`, `oidc`, `azureAD`,
53 * `githubOrganization`, `externalEvaluation`, `authContext`) keep their
54 * wire shape — there is no scalar to collapse them to.
55 */
56 export type PolicyRuleShorthand =
57 | "everyone"
58 | "certificate"
59 | "anyValidServiceToken"
60 | { email: string }
61 | { emailDomain: string }
62 | { emailList: string }
63 | { ip: string }
64 | { ipList: string }
65 | { group: string }
66 | { loginMethod: string }
67 | { serviceToken: string }
68 | { geo: string }
69 | { authMethod: string }
70 | { devicePosture: string }
71 | { commonName: string }
72 | { linkedAppToken: string }
73 | { userRiskScore: string }
74 | { cloudflareAccountMember: string };
75
76 /** A rule in either spelling: Cloudflare's wire shape or the scalar shorthand. */
77 export type PolicyRuleInput = PolicyRule | PolicyRuleShorthand;
78 export type PolicyExcludeRuleInput = PolicyExcludeRule | PolicyRuleShorthand;
79 export type PolicyRequireRuleInput = PolicyRequireRule | PolicyRuleShorthand;
80
81 /** Rule kind → its single parameter's (camelCase) member name. */
82 const SCALAR_RULE_PARAMS: Record<string, string> = {
83 email: "email",
84 emailDomain: "domain",
85 emailList: "id",
86 ip: "ip",
87 ipList: "id",
88 group: "id",
89 loginMethod: "id",
90 serviceToken: "tokenId",
91 geo: "countryCode",
92 authMethod: "authMethod",
93 devicePosture: "integrationUid",
94 commonName: "commonName",
95 linkedAppToken: "appUid",
96 userRiskScore: "userRiskScore",
97 cloudflareAccountMember: "accountId",
98 };
99
100 /**
101 * Expand the scalar shorthand to Cloudflare's wire shape; wire-shaped rules
102 * pass through untouched.
103 */
104 export const normalizePolicyRule = <Rule>(rule: Rule | PolicyRuleShorthand): Rule => {
105 if (typeof rule === "string") {
106 // "everyone" -> { everyone: {} }
107 return { [rule]: {} } as Rule;
108 }
109 const keys = Object.keys(rule as object);
110 if (keys.length === 1) {
111 const kind = keys[0];
112 const value = (rule as Record<string, unknown>)[kind];
113 const param = SCALAR_RULE_PARAMS[kind];
114 if (param !== undefined && (value === null || typeof value !== "object")) {
115 return { [kind]: { [param]: value } } as Rule;
116 }
117 }
118 return rule as Rule;
119 };
120
121 export function normalizePolicyRules<Rule>(
122 rules: ReadonlyArray<Rule | PolicyRuleShorthand>,
123 ): Rule[];
124 export function normalizePolicyRules<Rule>(
125 rules: ReadonlyArray<Rule | PolicyRuleShorthand> | undefined,
126 ): Rule[] | undefined;
127 export function normalizePolicyRules<Rule>(
128 rules: ReadonlyArray<Rule | PolicyRuleShorthand> | undefined,
129 ): Rule[] | undefined {
130 return rules === undefined ? undefined : rules.map((r) => normalizePolicyRule(r));
131 }
132
133 /**
134 * Decision Cloudflare Access takes when a request matches this policy.
135 *
136 * - `"allow"` — admit the user.
137 * - `"deny"` — block the user.
138 * - `"non_identity"` — admit without requiring an identity provider login.
139 * - `"bypass"` — skip Access entirely.
140 */
141 export type PolicyDecision =
142 | "allow"
143 | "deny"
144 | "non_identity"
145 | "bypass"
146 // Match distilled's open-ended literal union so Cloudflare-returned values
147 // outside the closed set still narrow cleanly.
148 | (string & {});
149
150 export type PolicyApprovalGroup = NonNullable<
151 zeroTrust.CreateAccessPolicyRequest["approvalGroups"]
152 >[number];
153 export type PolicyConnectionRules = NonNullable<
154 zeroTrust.CreateAccessPolicyRequest["connectionRules"]
155 >;
156 export type PolicyMfaConfig = NonNullable<zeroTrust.CreateAccessPolicyRequest["mfaConfig"]>;
157
158 export type PolicyProps = {
159 /**
160 * Display name for the policy. Treated as a stable identifier so the
161 * provider can locate the policy by name during adoption / state recovery.
162 * If omitted, a unique name is generated from the stack/stage/logical id.
163 *
164 * @default ${app}-${stage}-${id}
165 */
166 name?: string;
167 /**
168 * Decision the policy enforces when its rules match. Changing the decision
169 * triggers replacement.
170 */
171 decision: PolicyDecision;
172 /**
173 * Rules combined with logical OR. A request must satisfy at least one
174 * include rule for the policy to match. Required and must be non-empty.
175 */
176 include: PolicyRuleInput[];
177 /**
178 * Rules combined with logical NOT. A request matching any exclude rule is
179 * rejected by the policy even if it satisfied an include rule.
180 */
181 exclude?: PolicyExcludeRuleInput[];
182 /**
183 * Rules combined with logical AND. A request must satisfy every require
184 * rule in addition to an include rule.
185 */
186 require?: PolicyRequireRuleInput[];
187 /**
188 * Duration of issued session tokens. Format: `300ms`, `2h45m`, etc. When
189 * unset, applications using this policy fall back to their own configured
190 * session duration.
191 */
192 sessionDuration?: string;
193 /**
194 * When true, Access requires an administrator to approve each authentication
195 * request before the user is admitted.
196 *
197 * @default false
198 */
199 approvalRequired?: boolean;
200 /**
201 * When true, users must enter a justification when logging in to any
202 * application that consumes this policy.
203 *
204 * @default false
205 */
206 purposeJustificationRequired?: boolean;
207 /**
208 * Custom message shown on the purpose justification screen.
209 */
210 purposeJustificationPrompt?: string;
211 /**
212 * Administrators who can approve a temporary authentication request.
213 */
214 approvalGroups?: PolicyApprovalGroup[];
215 /**
216 * Serve applications in an isolated browser for users matching this
217 * policy. Requires Clientless Web Isolation on the account.
218 *
219 * @default false
220 */
221 isolationRequired?: boolean;
222 /**
223 * How users may connect to targets secured by an infrastructure
224 * application: allowed SSH usernames, RDP clipboard formats.
225 *
226 * @example
227 * ```ts
228 * connectionRules: { ssh: { usernames: ["root", "ubuntu"] } }
229 * ```
230 */
231 connectionRules?: PolicyConnectionRules;
232 /**
233 * Multi-factor authentication settings enforced by this policy.
234 */
235 mfaConfig?: PolicyMfaConfig;
236 /**
237 * Adopt an existing reusable policy with the same name when the engine has
238 * no prior state for this logical id.
239 *
240 * @default false
241 */
242 adopt?: boolean;
243 };
244
245 export declare namespace Policy {
246 /**
247 * A single Access policy rule. See {@link PolicyRule} for the full
248 * discriminated union (email, emailDomain, everyone, ip, ipList, group,
249 * gsuite, githubOrganization, okta, azureAD, saml, oidc, deviceCheck via
250 * `devicePosture`, externalEvaluation, etc.).
251 */
252 export type RuleGroup = PolicyRuleInput;
253 }
254
255 export type Policy = Resource<
256 "Cloudflare.Access.Policy",
257 PolicyProps,
258 {
259 /** UUID of the policy assigned by Cloudflare. */
260 policyId: string;
261 /** Display name reported by Cloudflare. */
262 name: string;
263 /** Decision the policy enforces. */
264 decision: string;
265 /** Cloudflare account that owns the policy. */
266 accountId: string;
267 /** Creation timestamp reported by Cloudflare, when available. */
268 createdAt: string | undefined;
269 /** Last-modified timestamp reported by Cloudflare, when available. */
270 updatedAt: string | undefined;
271 },
272 never,
273 Providers
274 >;
275
276 /**
277 * A reusable, account-scoped Cloudflare Access policy. Distinct from the
278 * inline policies attached directly to an `Application` — a reusable
279 * policy can be referenced by multiple applications by id.
280 *
281 * Optional fields you leave out keep their live value on update, so adopting
282 * a policy never drops rules you did not declare. Pass `[]` or `false` to
283 * clear one.
284 *
285 * ### Creating a Policy
286 * **Example:** Allow a single email domain
287 * ```typescript
288 * const policy = yield* Cloudflare.Access.Policy("AllowExampleDomain", {
289 * decision: "allow",
290 * include: [{ emailDomain: { domain: "example.com" } }],
291 * });
292 * ```
293 *
294 * **Example:** Allow everyone but require purpose justification
295 * ```typescript
296 * const policy = yield* Cloudflare.Access.Policy("OpenWithJustification", {
297 * decision: "allow",
298 * include: [{ everyone: {} }],
299 * purposeJustificationRequired: true,
300 * sessionDuration: "12h",
301 * });
302 * ```
303 *
304 * ### Combining rule groups
305 * **Example:** Include + exclude + require
306 * ```typescript
307 * const policy = yield* Cloudflare.Access.Policy("EngineersExceptInterns", {
308 * decision: "allow",
309 * include: [{ emailDomain: { domain: "example.com" } }],
310 * exclude: [{ email: { email: "intern@example.com" } }],
311 * require: [{ geo: { countryCode: "US" } }],
312 * });
313 * ```
314 *
315 * ### Infrastructure access
316 * **Example:** Allow SSH as specific Unix users
317 * ```typescript
318 * const policy = yield* Cloudflare.Access.Policy("SshOps", {
319 * decision: "allow",
320 * include: [{ emailDomain: "example.com" }],
321 * connectionRules: {
322 * ssh: { usernames: ["root", "ubuntu"], allowEmailAlias: true },
323 * },
324 * });
325 * ```
326 *
327 * @resource
328 * @product Access
329 * @category Cloudflare One (Zero Trust)
330 */
331 export const Policy = Resource<Policy>("Cloudflare.Access.Policy", {
332 aliases: ["Cloudflare.AccessPolicy"],
333 });
334
335 export const PolicyProvider = () =>
336 Provider.succeed(Policy, {
337 stables: ["policyId", "accountId", "decision"],
338 diff: Effect.fn(function* ({ id, olds = {}, news, output }) {
339 const { accountId } = yield* yield* CloudflareEnvironment;
340 if (!isResolved(news)) return undefined;
341 if ((output?.accountId ?? accountId) !== accountId) {
342 return { action: "replace" } as const;
343 }
344 const oldName = output?.name ?? (yield* createPolicyName(id, olds.name));
345 // Auto-generated names are engine-owned: the deployed name stays
346 // authoritative even if the generator would name this id differently
347 // today. Only an explicit user-provided name can force a replace.
348 const name = news.name ?? oldName;
349 if (name !== oldName) {
350 return { action: "replace" } as const;
351 }
352 const oldDecision = output?.decision ?? olds.decision;
353 if (oldDecision && oldDecision !== news.decision) {
354 return { action: "replace" } as const;
355 }
356 }),
357 reconcile: Effect.fn(function* ({ id, news = {} as PolicyProps, output }) {
358 const { accountId } = yield* yield* CloudflareEnvironment;
359 // Prefer the deployed name: regenerating would target a different
360 // resource if the generator's output for this id ever drifts.
361 const name = yield* createPolicyName(id, news.name ?? output?.name);
362 const acct = output?.accountId ?? accountId;
363
364 // Observe — prefer cached policyId, fall back to a name lookup so
365 // we recover from out-of-band deletes and partial state-persistence
366 // failures.
367 let observed: RawPolicy | undefined;
368 if (output?.policyId) {
369 observed = yield* zeroTrust
370 .getAccessPolicy({
371 accountId: acct,
372 policyId: output.policyId,
373 })
374 .pipe(Effect.orElseSucceed((): RawPolicy | undefined => undefined));
375 }
376 if (!observed) {
377 observed = yield* findPolicyByName(acct, name);
378 }
379
380 // Ensure — create the policy if missing. Tolerate a race where a
381 // parallel actor created the same-named policy by re-observing.
382 let ensured: ObservedPolicy;
383 if (!observed || !observed.id) {
384 ensured = yield* zeroTrust
385 .createAccessPolicy({ accountId: acct, ...policyBody(name, news) })
386 .pipe(
387 Effect.map(toObserved),
388 Effect.catch((err) =>
389 Effect.gen(function* () {
390 const existing = yield* findPolicyByName(acct, name);
391 if (existing && existing.id) return existing;
392 return yield* err;
393 }),
394 ),
395 );
396 } else {
397 // Sync — Cloudflare PUTs the policy as a whole replacement and
398 // resets every field the body omits, so undeclared optional fields
399 // are sent back with their live value.
400 const prior = observed;
401 const updated = yield* zeroTrust.updateAccessPolicy({
402 accountId: acct,
403 policyId: prior.id!,
404 ...withLiveFields(policyBody(name, news), prior),
405 });
406 ensured = {
407 id: updated.id ?? prior.id,
408 name: updated.name ?? prior.name,
409 decision: updated.decision ?? prior.decision,
410 createdAt: updated.createdAt ?? prior.createdAt,
411 updatedAt: updated.updatedAt ?? prior.updatedAt,
412 };
413 }
414
415 if (!ensured.id) {
416 return yield* new PolicyUnexpectedResponse({
417 message: "Policy: ensured policy missing id",
418 });
419 }
420 return {
421 policyId: ensured.id,
422 name: ensured.name ?? name,
423 decision: ensured.decision ?? news.decision,
424 accountId: acct,
425 createdAt: ensured.createdAt ?? undefined,
426 updatedAt: ensured.updatedAt ?? undefined,
427 };
428 }),
429 // Account-scoped collection (pattern (b)): enumerate every reusable
430 // Access policy in the ambient account, exhaustively paginated, and
431 // hydrate each into the exact `read` Attributes shape. Items missing the
432 // mandatory id are skipped (typed per-item drop).
433 list: Effect.fn(function* () {
434 const { accountId } = yield* yield* CloudflareEnvironment;
435 return yield* zeroTrust.listAccessPolicies.pages({ accountId }).pipe(
436 Stream.runCollect,
437 Effect.map((chunk) =>
438 Array.from(chunk).flatMap((page) =>
439 (page.result ?? []).flatMap((raw) => {
440 const observed = toObserved(raw as RawPolicy);
441 if (!observed.id) return [];
442 return [
443 {
444 policyId: observed.id,
445 name: observed.name ?? "",
446 decision: observed.decision ?? "allow",
447 accountId,
448 createdAt: observed.createdAt ?? undefined,
449 updatedAt: observed.updatedAt ?? undefined,
450 },
451 ];
452 }),
453 ),
454 ),
455 );
456 }),
457 delete: Effect.fn(function* ({ output }) {
458 yield* zeroTrust
459 .deleteAccessPolicy({
460 accountId: output.accountId,
461 policyId: output.policyId,
462 })
463 .pipe(Effect.catch((): Effect.Effect<void> => Effect.void));
464 }),
465 read: Effect.fn(function* ({ id, output, olds }) {
466 const { accountId } = yield* yield* CloudflareEnvironment;
467 const acct = output?.accountId ?? accountId;
468 if (output?.policyId) {
469 const direct = yield* zeroTrust
470 .getAccessPolicy({
471 accountId: acct,
472 policyId: output.policyId,
473 })
474 .pipe(Effect.orElseSucceed((): ObservedPolicy | undefined => undefined));
475 if (direct && direct.id) {
476 return {
477 policyId: direct.id,
478 name: direct.name ?? output.name,
479 decision: direct.decision ?? output.decision,
480 accountId: acct,
481 createdAt: direct.createdAt ?? output.createdAt,
482 updatedAt: direct.updatedAt ?? output.updatedAt,
483 };
484 }
485 }
486 const name = yield* createPolicyName(id, olds?.name ?? output?.name);
487 const existing = yield* findPolicyByName(acct, name);
488 if (!existing || !existing.id) return undefined;
489 return {
490 policyId: existing.id,
491 name: existing.name ?? name,
492 decision: existing.decision ?? olds?.decision ?? "allow",
493 accountId: acct,
494 createdAt: existing.createdAt ?? undefined,
495 updatedAt: existing.updatedAt ?? undefined,
496 };
497 }),
498 });
499
500 const policyBody = (name: string, news: PolicyProps) => ({
501 name,
502 decision: news.decision,
503 include: normalizePolicyRules(news.include),
504 exclude: normalizePolicyRules(news.exclude),
505 require: normalizePolicyRules(news.require),
506 sessionDuration: news.sessionDuration,
507 approvalRequired: news.approvalRequired,
508 approvalGroups: news.approvalGroups,
509 isolationRequired: news.isolationRequired,
510 purposeJustificationRequired: news.purposeJustificationRequired,
511 purposeJustificationPrompt: news.purposeJustificationPrompt,
512 connectionRules: news.connectionRules,
513 mfaConfig: news.mfaConfig,
514 });
515
516 // Optional fields a whole-replacement PUT would reset when omitted.
517 const PRESERVED_FIELDS = [
518 "exclude",
519 "require",
520 "sessionDuration",
521 "approvalRequired",
522 "approvalGroups",
523 "isolationRequired",
524 "purposeJustificationRequired",
525 "purposeJustificationPrompt",
526 "connectionRules",
527 "mfaConfig",
528 ] as const;
529
530 const withLiveFields = (
531 body: ReturnType<typeof policyBody>,
532 live: RawPolicy,
533 ): ReturnType<typeof policyBody> => ({
534 ...body,
535 ...Object.fromEntries(
536 PRESERVED_FIELDS.flatMap((key) =>
537 body[key] === undefined && live[key] != null ? [[key, stripNullFields(live[key])]] : [],
538 ),
539 ),
540 });
541
542 const createPolicyName = (id: string, name: string | undefined) =>
543 Effect.gen(function* () {
544 if (name) return name;
545 return yield* createPhysicalName({ id });
546 });
547
548 const findPolicyByName = (acct: string, name: string) =>
549 zeroTrust.listAccessPolicies.items({ accountId: acct }).pipe(
550 Stream.filter((p) => p.name === name),
551 Stream.runHead,
552 Effect.map(Option.getOrUndefined),
553 Effect.orElseSucceed(() => undefined),
554 );
555
556 type ObservedPolicy = {
557 id?: string | null;
558 name?: string | null;
559 decision?: PolicyDecision | null;
560 createdAt?: string | null;
561 updatedAt?: string | null;
562 };
563
564 // Distilled response shapes (Get / List / Create / Update) all carry the same
565 // set of fields we care about, but typed wider than `ObservedPolicy`. Narrow
566 // at the API boundary so the rest of the reconciler stays in our shape.
567 type RawPolicy = {
568 id?: string | null;
569 name?: string | null;
570 decision?: string | null;
571 createdAt?: string | null;
572 updatedAt?: string | null;
573 } & { [K in (typeof PRESERVED_FIELDS)[number]]?: unknown };
574
575 const toObserved = (r: RawPolicy): ObservedPolicy => ({
576 id: r.id,
577 name: r.name,
578 decision: r.decision ?? null,
579 createdAt: r.createdAt,
580 updatedAt: r.updatedAt,
581 });