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

main
ts 339 lines 12.7 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 Redacted from "effect/Redacted";
10 import * as Stream from "effect/Stream";
11 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
12 import type { Providers } from "../Providers.ts";
13
14 const TypeId = "Cloudflare.VulnerabilityScanner.Credential" as const;
15 type TypeId = typeof TypeId;
16
17 /**
18 * Where the scanner attaches a credential in outgoing requests.
19 */
20 export type VulnScannerCredentialLocation = "header" | "cookie";
21
22 export interface VulnScannerCredentialProps {
23 /**
24 * The credential set this credential belongs to. The parent is part of
25 * the credential's API path, so changing it triggers a replacement.
26 */
27 credentialSetId: string;
28 /**
29 * Human-readable name for the credential. If omitted, a unique name is
30 * generated from the app, stage, and logical ID.
31 * @default ${app}-${stage}-${id}
32 */
33 name?: string;
34 /**
35 * Where the credential is attached in outgoing requests: as an HTTP
36 * `header` or a `cookie`. Mutable.
37 */
38 location: VulnScannerCredentialLocation;
39 /**
40 * Name of the header or cookie the credential is attached as
41 * (e.g. `authorization`, `session_id`). Cloudflare requires the name in
42 * normalized (lowercase) form and rejects e.g. `Authorization` with a
43 * `BadRequest`. Mutable.
44 */
45 locationName: string;
46 /**
47 * The credential value (e.g. API key, session token). Write-only — the
48 * Cloudflare API never returns it, so rotation is detected by comparing
49 * against the previously deployed value.
50 */
51 value: Redacted.Redacted<string>;
52 }
53
54 export interface VulnScannerCredentialAttributes {
55 /** Server-assigned credential identifier (UUID). */
56 credentialId: string;
57 /** The parent credential set identifier. */
58 credentialSetId: string;
59 /** The Cloudflare account the credential belongs to. */
60 accountId: string;
61 /** Human-readable name. */
62 name: string;
63 /** Where the credential is attached in outgoing requests. */
64 location: VulnScannerCredentialLocation;
65 /** Name of the header or cookie the credential is attached as. */
66 locationName: string;
67 }
68
69 export type VulnScannerCredential = Resource<
70 TypeId,
71 VulnScannerCredentialProps,
72 VulnScannerCredentialAttributes,
73 never,
74 Providers
75 >;
76
77 /**
78 * A credential inside a Cloudflare Vulnerability Scanner credential set —
79 * an HTTP header or cookie value the DAST scanner attaches to outgoing
80 * requests so it can scan authenticated surfaces.
81 *
82 * The credential `value` is write-only: Cloudflare never returns it, so the
83 * provider rotates it by comparing the desired value against the previously
84 * deployed one. `name`, `location`, and `locationName` are mutable in place;
85 * moving the credential to a different set triggers a replacement.
86 * ### Creating a Credential
87 * **Example:** Authorization header
88 * ```typescript
89 * const creds = yield* Cloudflare.VulnerabilityScanner.VulnScannerCredentialSet("scanner-creds", {});
90 *
91 * const apiKey = yield* Cloudflare.VulnerabilityScanner.VulnScannerCredential("api-key", {
92 * credentialSetId: creds.credentialSetId,
93 * location: "header",
94 * // Cloudflare requires normalized (lowercase) header/cookie names.
95 * locationName: "authorization",
96 * value: Redacted.make("Bearer my-api-key"),
97 * });
98 * ```
99 *
100 * **Example:** Session cookie
101 * ```typescript
102 * const session = yield* Cloudflare.VulnerabilityScanner.VulnScannerCredential("session", {
103 * credentialSetId: creds.credentialSetId,
104 * location: "cookie",
105 * locationName: "session_id",
106 * value: Redacted.make("s3cr3t-session-token"),
107 * });
108 * ```
109 *
110 * ### Rotating the Value
111 * **Example:** Rotate by redeploying with a new value
112 * ```typescript
113 * // Change the redacted value and redeploy — the provider PUTs the new
114 * // value even though the API never echoes it back.
115 * const rotated = yield* Cloudflare.VulnerabilityScanner.VulnScannerCredential("api-key", {
116 * credentialSetId: creds.credentialSetId,
117 * location: "header",
118 * locationName: "authorization",
119 * value: Redacted.make("Bearer my-new-api-key"),
120 * });
121 * ```
122 *
123 * @see https://developers.cloudflare.com/security-center/
124 *
125 * @resource
126 * @product Vulnerability Scanner
127 * @category Application Security
128 */
129 export const VulnScannerCredential = Resource<VulnScannerCredential>(TypeId);
130
131 /**
132 * Returns true if the given value is a VulnScannerCredential resource.
133 */
134 export const isVulnScannerCredential = (value: unknown): value is VulnScannerCredential =>
135 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
136
137 export const VulnScannerCredentialProvider = () =>
138 Provider.succeed(VulnScannerCredential, {
139 stables: ["credentialId", "credentialSetId", "accountId"],
140
141 // Credentials are sub-resources of a credential set and there is no
142 // account-wide credential list. Enumerate every credential set in the
143 // account, then fan out the per-set credential list and flatten. The
144 // write-only `value` is never returned, so each row matches the exact
145 // shape `read` produces.
146 list: Effect.fn(function* () {
147 const { accountId } = yield* yield* CloudflareEnvironment;
148 const setIds = yield* vulnScanner.listCredentialSets.pages({ accountId }).pipe(
149 Stream.runCollect,
150 Effect.map((chunk) =>
151 Array.from(chunk).flatMap((page) => (page.result ?? []).map((set) => set.id)),
152 ),
153 );
154 const rows = yield* Effect.forEach(
155 setIds,
156 (credentialSetId) =>
157 vulnScanner.listCredentialSetCredentials.pages({ accountId, credentialSetId }).pipe(
158 Stream.runCollect,
159 Effect.map((chunk) =>
160 Array.from(chunk).flatMap((page) =>
161 (page.result ?? []).map((c) => toAttributes(c, accountId)),
162 ),
163 ),
164 // A set deleted mid-enumeration, or one we cannot access
165 // (entitlement / permissions), contributes nothing.
166 Effect.catchTag(["CredentialSetNotFound", "Forbidden"], () =>
167 Effect.succeed([] as VulnScannerCredentialAttributes[]),
168 ),
169 ),
170 { concurrency: 10 },
171 );
172 return rows.flat();
173 }),
174
175 diff: Effect.fn(function* ({ news, output }) {
176 const { accountId } = yield* yield* CloudflareEnvironment;
177 if (!isResolved(news)) return undefined;
178 if ((output?.accountId ?? accountId) !== accountId) {
179 return { action: "replace" } as const;
180 }
181 // The parent set is part of the credential's API path — a credential
182 // cannot be moved between sets in place.
183 if (
184 output?.credentialSetId !== undefined &&
185 typeof news.credentialSetId === "string" &&
186 news.credentialSetId !== output.credentialSetId
187 ) {
188 return { action: "replace" } as const;
189 }
190 return undefined;
191 }),
192
193 read: Effect.fn(function* ({ id, output, olds }) {
194 const { accountId } = yield* yield* CloudflareEnvironment;
195 const acct = output?.accountId ?? accountId;
196
197 // Owned path: refresh by the persisted UUIDs.
198 if (output?.credentialId && output.credentialSetId) {
199 const observed = yield* observeCredential(
200 acct,
201 output.credentialSetId,
202 output.credentialId,
203 );
204 return observed ? toAttributes(observed, acct) : undefined;
205 }
206
207 // Cold read: we need the parent set to look anything up. Match the
208 // deterministic physical name within the set; names carry no
209 // ownership markers, so gate takeover behind the adopt policy.
210 const credentialSetId =
211 output?.credentialSetId ??
212 (typeof olds?.credentialSetId === "string" ? olds.credentialSetId : undefined);
213 if (!credentialSetId) return undefined;
214 const name = yield* createCredentialName(id, olds?.name);
215 const match = yield* findCredentialByName(acct, credentialSetId, name);
216 return match ? Unowned(toAttributes(match, acct)) : undefined;
217 }),
218
219 reconcile: Effect.fn(function* ({ id, news, output, olds }) {
220 const { accountId } = yield* yield* CloudflareEnvironment;
221 const name = yield* createCredentialName(id, news.name);
222 // Inputs are resolved to concrete values by the engine.
223 const credentialSetId = news.credentialSetId as string;
224 const value = Redacted.value(news.value);
225
226 // 1. Observe — cached UUID first, then deterministic name within the
227 // parent set (recovers from a crash between create and state
228 // persistence). A deleted parent set surfaces the credential as
229 // missing and falls through to create.
230 let observed = output?.credentialId
231 ? yield* observeCredential(
232 output.accountId ?? accountId,
233 credentialSetId,
234 output.credentialId,
235 )
236 : undefined;
237 if (!observed) {
238 observed = yield* findCredentialByName(accountId, credentialSetId, name);
239 }
240
241 // 2. Ensure — create when missing.
242 if (!observed) {
243 const created = yield* vulnScanner.createCredentialSetCredential({
244 accountId,
245 credentialSetId,
246 name,
247 location: news.location,
248 locationName: news.locationName,
249 value,
250 });
251 return toAttributes(created, accountId);
252 }
253
254 // 3. Sync — PUT the full body (the API requires `value` on PUT) when
255 // any observable field drifts, or when the write-only value
256 // changed between olds and news. The value is never readable, so
257 // `olds.value` is the one sanctioned baseline for rotation.
258 const oldValue = olds?.value === undefined ? undefined : Redacted.value(olds.value);
259 const valueChanged = oldValue !== value;
260 const dirty =
261 observed.name !== name ||
262 observed.location !== news.location ||
263 observed.locationName !== news.locationName ||
264 valueChanged;
265 if (dirty) {
266 const updated = yield* vulnScanner.updateCredentialSetCredential({
267 accountId,
268 credentialSetId,
269 credentialId: observed.id,
270 name,
271 location: news.location,
272 locationName: news.locationName,
273 value,
274 });
275 return toAttributes(updated, accountId);
276 }
277
278 // 4. Return.
279 return toAttributes(observed, accountId);
280 }),
281
282 delete: Effect.fn(function* ({ output }) {
283 yield* vulnScanner
284 .deleteCredentialSetCredential({
285 accountId: output.accountId,
286 credentialSetId: output.credentialSetId,
287 credentialId: output.credentialId,
288 })
289 .pipe(
290 // Both "credential gone" and "parent set already gone" mean the
291 // credential no longer exists — idempotent success.
292 Effect.catchTag(["CredentialNotFound", "CredentialSetNotFound"], () => Effect.void),
293 );
294 }),
295 });
296
297 /**
298 * Read a credential by id, mapping "gone" (`CredentialNotFound` 14002, or
299 * the parent set gone, `CredentialSetNotFound` 14001) to `undefined`.
300 */
301 const observeCredential = (accountId: string, credentialSetId: string, credentialId: string) =>
302 vulnScanner
303 .getCredentialSetCredential({ accountId, credentialSetId, credentialId })
304 .pipe(Effect.catchTag(["CredentialNotFound", "CredentialSetNotFound"], () => Effect.undefined));
305
306 /**
307 * Find a credential by exact name within a set. Names are not unique on
308 * Cloudflare's side; if several match, pick the lexicographically smallest
309 * id for determinism. A missing parent set reads as "no match".
310 */
311 const findCredentialByName = (accountId: string, credentialSetId: string, name: string) =>
312 vulnScanner.listCredentialSetCredentials.items({ accountId, credentialSetId }).pipe(
313 Stream.filter((c) => c.name === name),
314 Stream.runCollect,
315 Effect.map((chunk) =>
316 Array.from(chunk)
317 .sort((a, b) => a.id.localeCompare(b.id))
318 .at(0),
319 ),
320 Effect.catchTag("CredentialSetNotFound", () => Effect.undefined),
321 );
322
323 const createCredentialName = (id: string, name: string | undefined) =>
324 Effect.gen(function* () {
325 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
326 });
327
328 const toAttributes = (
329 credential: vulnScanner.GetCredentialSetCredentialResponse,
330 accountId: string,
331 ): VulnScannerCredentialAttributes => ({
332 credentialId: credential.id,
333 credentialSetId: credential.credentialSetId,
334 accountId,
335 name: credential.name,
336 // Distilled widens generated string enums to open unions (`string & {}`).
337 location: credential.location as VulnScannerCredentialLocation,
338 locationName: credential.locationName,
339 });