@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, 04:45 UTC

main
ts 262 lines 9.36 KB
Raw
1 import * as vulnScanner from "@distilled.cloud/cloudflare/vulnerability-scanner";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Effect from "effect/Effect";
8 import * as Predicate from "effect/Predicate";
9 import * as Stream from "effect/Stream";
10 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
11 import type { Providers } from "../Providers.ts";
12
13 const TypeId = "Cloudflare.VulnerabilityScanner.TargetEnvironment" as const;
14 type TypeId = typeof TypeId;
15
16 export interface VulnScannerTargetEnvironmentProps {
17 /**
18 * Human-readable name for the target environment. If omitted, a unique
19 * name is generated from the app, stage, and logical ID.
20 * @default ${app}-${stage}-${id}
21 */
22 name?: string;
23 /**
24 * The zone the scanner targets (`target.zone_tag`). Scan history is tied
25 * to the target, so changing the zone triggers a replacement.
26 */
27 zoneId: string;
28 /**
29 * Optional description providing additional context. Mutable; omit to
30 * clear an existing description.
31 */
32 description?: string;
33 }
34
35 export interface VulnScannerTargetEnvironmentAttributes {
36 /** Server-assigned target environment identifier (UUID). */
37 targetEnvironmentId: string;
38 /** The Cloudflare account the target environment belongs to. */
39 accountId: string;
40 /** Human-readable name. */
41 name: string;
42 /** The zone being scanned (`target.zone_tag`). */
43 zoneId: string;
44 /** Description, if set. */
45 description: string | undefined;
46 }
47
48 export type VulnScannerTargetEnvironment = Resource<
49 TypeId,
50 VulnScannerTargetEnvironmentProps,
51 VulnScannerTargetEnvironmentAttributes,
52 never,
53 Providers
54 >;
55
56 /**
57 * A Cloudflare Vulnerability Scanner target environment — declares which
58 * zone the DAST-style web vulnerability scanner (Security Center, beta) is
59 * allowed to scan.
60 *
61 * The environment is identified by a server-assigned UUID. `name` and
62 * `description` are mutable in place; changing the target `zoneId` triggers
63 * a replacement because scan history is tied to the target.
64 * ### Creating a Target Environment
65 * **Example:** Scan a zone
66 * ```typescript
67 * const zone = yield* Cloudflare.Zone.Zone("site", { name: "example.com" });
68 *
69 * const target = yield* Cloudflare.VulnerabilityScanner.VulnScannerTargetEnvironment("site-scans", {
70 * zoneId: zone.zoneId,
71 * });
72 * ```
73 *
74 * **Example:** With an explicit name and description
75 * ```typescript
76 * const target = yield* Cloudflare.VulnerabilityScanner.VulnScannerTargetEnvironment("site-scans", {
77 * name: "production-site",
78 * zoneId: zone.zoneId,
79 * description: "Weekly DAST scan of the production zone",
80 * });
81 * ```
82 *
83 * @see https://developers.cloudflare.com/security-center/
84 *
85 * @resource
86 * @product Vulnerability Scanner
87 * @category Application Security
88 */
89 export const VulnScannerTargetEnvironment = Resource<VulnScannerTargetEnvironment>(TypeId);
90
91 /**
92 * Returns true if the given value is a VulnScannerTargetEnvironment resource.
93 */
94 export const isVulnScannerTargetEnvironment = (
95 value: unknown,
96 ): value is VulnScannerTargetEnvironment =>
97 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
98
99 export const VulnScannerTargetEnvironmentProvider = () =>
100 Provider.succeed(VulnScannerTargetEnvironment, {
101 stables: ["targetEnvironmentId", "accountId"],
102
103 // Account collection: exhaustively paginate the account-scoped target
104 // environments list and hydrate each row into the `read` Attributes shape.
105 list: Effect.fn(function* () {
106 const { accountId } = yield* yield* CloudflareEnvironment;
107 return yield* vulnScanner.listTargetEnvironments.pages({ accountId }).pipe(
108 Stream.runCollect,
109 Effect.map((chunk) =>
110 Array.from(chunk).flatMap((page) =>
111 (page.result ?? []).map((env) => toAttributes(env, accountId)),
112 ),
113 ),
114 );
115 }),
116
117 diff: Effect.fn(function* ({ news, output }) {
118 const { accountId } = yield* yield* CloudflareEnvironment;
119 if (!isResolved(news)) return undefined;
120 if ((output?.accountId ?? accountId) !== accountId) {
121 return { action: "replace" } as const;
122 }
123 // The scan target is the environment's identity — scan history is
124 // tied to it, so a different zone means a different environment.
125 if (
126 output?.zoneId !== undefined &&
127 typeof news.zoneId === "string" &&
128 news.zoneId !== output.zoneId
129 ) {
130 return { action: "replace" } as const;
131 }
132 return undefined;
133 }),
134
135 read: Effect.fn(function* ({ id, output, olds }) {
136 const { accountId } = yield* yield* CloudflareEnvironment;
137 const acct = output?.accountId ?? accountId;
138
139 // Owned path: refresh by the persisted UUID.
140 if (output?.targetEnvironmentId) {
141 const observed = yield* observeTargetEnvironment(acct, output.targetEnvironmentId);
142 return observed ? toAttributes(observed, acct) : undefined;
143 }
144
145 // Cold read: recover from lost state by matching the deterministic
146 // physical name. Names carry no ownership markers, so report the
147 // match `Unowned` and let the engine gate takeover behind --adopt.
148 const name = yield* createEnvironmentName(id, olds?.name);
149 const match = yield* findTargetEnvironmentByName(acct, name);
150 return match ? Unowned(toAttributes(match, acct)) : undefined;
151 }),
152
153 reconcile: Effect.fn(function* ({ id, news, output }) {
154 const { accountId } = yield* yield* CloudflareEnvironment;
155 const name = yield* createEnvironmentName(id, news.name);
156 // Inputs are resolved to concrete values by the engine.
157 const zoneId = news.zoneId as string;
158
159 // 1. Observe — the UUID cached on `output` is a hint, not a
160 // guarantee: a not-found falls through to "missing".
161 let observed = output?.targetEnvironmentId
162 ? yield* observeTargetEnvironment(output.accountId ?? accountId, output.targetEnvironmentId)
163 : undefined;
164 // Fall back to the deterministic name (e.g. crash after create but
165 // before state persistence). Server UUIDs make duplicate-create the
166 // failure mode to defend against here.
167 if (!observed) {
168 observed = yield* findTargetEnvironmentByName(accountId, name);
169 }
170
171 // 2. Ensure — create when missing.
172 if (!observed) {
173 const created = yield* vulnScanner.createTargetEnvironment({
174 accountId,
175 name,
176 target: { type: "zone", zoneTag: zoneId },
177 description: news.description,
178 });
179 return toAttributes(created, accountId);
180 }
181
182 // 3. Sync — PUT the full desired body when anything drifts; skip the
183 // API call entirely on a no-op.
184 const desiredDescription = news.description;
185 const observedDescription = observed.description ?? undefined;
186 const dirty =
187 observed.name !== name ||
188 observed.target.zoneTag !== zoneId ||
189 observedDescription !== desiredDescription;
190 if (dirty) {
191 const updated = yield* vulnScanner.updateTargetEnvironment({
192 accountId,
193 targetEnvironmentId: observed.id,
194 name,
195 target: { type: "zone", zoneTag: zoneId },
196 // PUT with explicit null clears a stale description.
197 description: desiredDescription ?? null,
198 });
199 return toAttributes(updated, accountId);
200 }
201
202 // 4. Return.
203 return toAttributes(observed, accountId);
204 }),
205
206 delete: Effect.fn(function* ({ output }) {
207 yield* vulnScanner
208 .deleteTargetEnvironment({
209 accountId: output.accountId,
210 targetEnvironmentId: output.targetEnvironmentId,
211 })
212 .pipe(Effect.catchTag("TargetEnvironmentNotFound", () => Effect.void));
213 }),
214 });
215
216 interface ObservedTargetEnvironment {
217 readonly id: string;
218 readonly name: string;
219 readonly target: { readonly type: "zone"; readonly zoneTag: string };
220 readonly description?: string | null;
221 }
222
223 /**
224 * Read a target environment by id, mapping "gone" (`TargetEnvironmentNotFound`,
225 * Cloudflare error code 11001) to `undefined`.
226 */
227 const observeTargetEnvironment = (accountId: string, targetEnvironmentId: string) =>
228 vulnScanner
229 .getTargetEnvironment({ accountId, targetEnvironmentId })
230 .pipe(Effect.catchTag("TargetEnvironmentNotFound", () => Effect.undefined));
231
232 /**
233 * Find a target environment by exact name. Names are not unique on
234 * Cloudflare's side; if several match, pick the lexicographically smallest
235 * id for determinism.
236 */
237 const findTargetEnvironmentByName = (accountId: string, name: string) =>
238 vulnScanner.listTargetEnvironments.items({ accountId }).pipe(
239 Stream.filter((e) => e.name === name),
240 Stream.runCollect,
241 Effect.map((chunk): ObservedTargetEnvironment | undefined =>
242 Array.from(chunk)
243 .sort((a, b) => a.id.localeCompare(b.id))
244 .at(0),
245 ),
246 );
247
248 const createEnvironmentName = (id: string, name: string | undefined) =>
249 Effect.gen(function* () {
250 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
251 });
252
253 const toAttributes = (
254 env: ObservedTargetEnvironment,
255 accountId: string,
256 ): VulnScannerTargetEnvironmentAttributes => ({
257 targetEnvironmentId: env.id,
258 accountId,
259 name: env.name,
260 zoneId: env.target.zoneTag,
261 description: env.description ?? undefined,
262 });