@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 242 lines 7.92 KB
Raw
1 import * as cloudforceOne from "@distilled.cloud/cloudflare/cloudforce-one";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Predicate from "effect/Predicate";
7 import * as Stream from "effect/Stream";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10
11 const TypeId = "Cloudflare.CloudforceOne.ScanConfig" as const;
12 type TypeId = typeof TypeId;
13
14 export type ScanConfigProps = {
15 /**
16 * IP addresses or CIDR blocks to scan. The maximum number of total IP
17 * addresses allowed is 5000.
18 */
19 ips: string[];
20 /**
21 * Number of days between each scan (`0` = one-off scan).
22 * @default 0
23 */
24 frequency?: number;
25 /**
26 * Ports to scan. Valid values are `"default"` (the 100 most commonly open
27 * ports), `"all"`, or a list of ports / port ranges (e.g. `["1-80", "443"]`).
28 * @default ["default"]
29 */
30 ports?: string[];
31 };
32
33 export type ScanConfigAttributes = {
34 /**
35 * Server-assigned scan config identifier (UUID).
36 */
37 configId: string;
38 /**
39 * The Cloudflare account the scan config belongs to.
40 */
41 accountId: string;
42 /**
43 * IP addresses or CIDR blocks being scanned.
44 */
45 ips: string[];
46 /**
47 * Number of days between each scan (`0` = one-off scan).
48 */
49 frequency: number;
50 /**
51 * Ports being scanned.
52 */
53 ports: string[];
54 };
55
56 export type ScanConfig = Resource<TypeId, ScanConfigProps, ScanConfigAttributes, never, Providers>;
57
58 /**
59 * A Cloudforce One attack-surface scan configuration.
60 *
61 * Cloudforce One (Cloudflare's threat-intelligence product) can periodically
62 * port-scan IP addresses you own to map your attack surface. A scan config
63 * declares which IPs to scan, on which ports, and how often. Scan results are
64 * read back via the scan-results API; the config itself is the only
65 * declarative piece.
66 *
67 * Requires the `cfone.port_scan` entitlement (Cloudforce One subscription) —
68 * accounts without it receive an `Unauthorized` error for every scan-config
69 * operation.
70 * ### Creating a Scan Config
71 * **Example:** One-off scan of a single address
72 * ```typescript
73 * const scan = yield* Cloudflare.CloudforceOne.ScanConfig("edge-scan", {
74 * ips: ["203.0.113.7/32"],
75 * frequency: 0,
76 * });
77 * ```
78 *
79 * **Example:** Weekly scan of a CIDR block on specific ports
80 * ```typescript
81 * const scan = yield* Cloudflare.CloudforceOne.ScanConfig("perimeter", {
82 * ips: ["203.0.113.0/24"],
83 * frequency: 7,
84 * ports: ["1-80", "443"],
85 * });
86 * ```
87 *
88 * ### Updating
89 * **Example:** Change the schedule and port list in place
90 * ```typescript
91 * const scan = yield* Cloudflare.CloudforceOne.ScanConfig("perimeter", {
92 * ips: ["203.0.113.0/24"],
93 * frequency: 30,
94 * ports: ["all"],
95 * });
96 * ```
97 *
98 * @see https://developers.cloudflare.com/security-center/intel-apis/attack-surface-scans/
99 *
100 * @resource
101 * @product Cloudforce One
102 * @category Observability & Analytics
103 */
104 export const ScanConfig = Resource<ScanConfig>(TypeId);
105
106 /**
107 * Returns true if the given value is a ScanConfig resource.
108 */
109 export const isScanConfig = (value: unknown): value is ScanConfig =>
110 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
111
112 export const ScanConfigProvider = () =>
113 Provider.succeed(ScanConfig, {
114 stables: ["configId", "accountId"],
115 diff: Effect.fn(function* ({ news, output }) {
116 const { accountId } = yield* yield* CloudflareEnvironment;
117 if (!isResolved(news)) return undefined;
118 // Scan configs are account-scoped; moving accounts is a replacement.
119 if ((output?.accountId ?? accountId) !== accountId) {
120 return { action: "replace" } as const;
121 }
122 // ips / frequency / ports are all mutable via PATCH.
123 return undefined;
124 }),
125 read: Effect.fn(function* ({ output }) {
126 // There is no get-by-id endpoint and configs carry no name, so a cold
127 // read (lost state, no cached configId) has no identity to match — we
128 // can only observe through the cached configId.
129 if (!output?.configId) return undefined;
130 const acct = output.accountId;
131 const observed = yield* findConfig(acct, output.configId);
132 return observed ? toAttributes(observed, acct) : undefined;
133 }),
134 list: Effect.fn(function* () {
135 const { accountId } = yield* yield* CloudflareEnvironment;
136 return yield* cloudforceOne.listScanConfigs.pages({ accountId }).pipe(
137 Stream.runCollect,
138 Effect.map((chunk) =>
139 Array.from(chunk).flatMap((page) =>
140 (page.result ?? []).map((c) => toAttributes(c, accountId)),
141 ),
142 ),
143 // Accounts without the cfone.port_scan entitlement reject every
144 // scan-config call with the typed Unauthorized — treat as "none".
145 Effect.catchTag("Unauthorized", () => Effect.succeed<ScanConfigAttributes[]>([])),
146 );
147 }),
148 reconcile: Effect.fn(function* ({ news, output }) {
149 const { accountId } = yield* yield* CloudflareEnvironment;
150
151 // Observe — the configId cached on `output` is a hint, not a
152 // guarantee: missing from the list falls through to create.
153 const observed = output?.configId
154 ? yield* findConfig(output.accountId ?? accountId, output.configId)
155 : undefined;
156
157 if (!observed) {
158 // Ensure — greenfield (or out-of-band delete).
159 const created = yield* cloudforceOne.createScanConfig({
160 accountId,
161 ips: news.ips,
162 frequency: news.frequency,
163 ports: news.ports,
164 });
165 return toAttributes(created, accountId);
166 }
167
168 // Sync — diff observed cloud state against desired; PATCH accepts
169 // partial bodies, so send only what the user pinned, and skip the
170 // call entirely on a no-op.
171 const dirty =
172 !sameList(observed.ips, news.ips) ||
173 (news.frequency !== undefined && observed.frequency !== news.frequency) ||
174 (news.ports !== undefined && !sameList(observed.ports, news.ports));
175
176 if (!dirty) {
177 return toAttributes(observed, observed.accountId);
178 }
179
180 const updated = yield* cloudforceOne
181 .patchScanConfig({
182 accountId: observed.accountId,
183 configId: observed.id,
184 ips: news.ips,
185 frequency: news.frequency,
186 ports: news.ports,
187 })
188 .pipe(
189 // Deleted out-of-band between observe and patch — recreate.
190 Effect.catchTag("ScanConfigNotFound", () =>
191 cloudforceOne.createScanConfig({
192 accountId,
193 ips: news.ips,
194 frequency: news.frequency,
195 ports: news.ports,
196 }),
197 ),
198 );
199 return toAttributes(updated, observed.accountId);
200 }),
201 delete: Effect.fn(function* ({ output }) {
202 yield* cloudforceOne
203 .deleteScanConfig({
204 accountId: output.accountId,
205 configId: output.configId,
206 })
207 .pipe(Effect.catchTag("ScanConfigNotFound", () => Effect.void));
208 }),
209 });
210
211 type ObservedScanConfig = {
212 id: string;
213 accountId: string;
214 frequency: number;
215 ips: readonly string[];
216 ports: readonly string[];
217 };
218
219 /**
220 * Find a scan config by id. There is no get-by-id endpoint, so observe via
221 * the account-level list; absent from the list means gone.
222 */
223 const findConfig = (accountId: string, configId: string) =>
224 cloudforceOne
225 .listScanConfigs({ accountId })
226 .pipe(
227 Effect.map((page): ObservedScanConfig | undefined =>
228 page.result.find((c) => c.id === configId),
229 ),
230 );
231
232 const sameList = (observed: readonly string[], desired: readonly string[]) =>
233 observed.length === desired.length &&
234 [...observed].sort().join(",") === [...desired].sort().join(",");
235
236 const toAttributes = (config: ObservedScanConfig, accountId: string): ScanConfigAttributes => ({
237 configId: config.id,
238 accountId,
239 ips: [...config.ips],
240 frequency: config.frequency,
241 ports: [...config.ports],
242 });