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

main
ts 217 lines 7.25 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.CredentialSet" as const;
14 type TypeId = typeof TypeId;
15
16 export interface VulnScannerCredentialSetProps {
17 /**
18 * Human-readable name for the credential set. If omitted, a unique name
19 * is generated from the app, stage, and logical ID.
20 * @default ${app}-${stage}-${id}
21 */
22 name?: string;
23 }
24
25 export interface VulnScannerCredentialSetAttributes {
26 /** Server-assigned credential set identifier (UUID). */
27 credentialSetId: string;
28 /** The Cloudflare account the credential set belongs to. */
29 accountId: string;
30 /** Human-readable name. */
31 name: string;
32 }
33
34 export type VulnScannerCredentialSet = Resource<
35 TypeId,
36 VulnScannerCredentialSetProps,
37 VulnScannerCredentialSetAttributes,
38 never,
39 Providers
40 >;
41
42 /**
43 * A Cloudflare Vulnerability Scanner credential set — a named container for
44 * authentication credentials (headers/cookies) the DAST scanner attaches to
45 * outgoing requests when scanning authenticated surfaces.
46 *
47 * Add individual credentials to the set with
48 * {@link VulnScannerCredential | `Cloudflare.VulnerabilityScanner.VulnScannerCredential`}.
49 * ### Creating a Credential Set
50 * **Example:** Default name
51 * ```typescript
52 * const creds = yield* Cloudflare.VulnerabilityScanner.VulnScannerCredentialSet("scanner-creds", {});
53 * ```
54 *
55 * **Example:** Explicit name
56 * ```typescript
57 * const creds = yield* Cloudflare.VulnerabilityScanner.VulnScannerCredentialSet("scanner-creds", {
58 * name: "staging-credentials",
59 * });
60 * ```
61 *
62 * ### Adding Credentials
63 * **Example:** Authorization header credential
64 * ```typescript
65 * const apiKey = yield* Cloudflare.VulnerabilityScanner.VulnScannerCredential("api-key", {
66 * credentialSetId: creds.credentialSetId,
67 * location: "header",
68 * locationName: "authorization", // Cloudflare requires lowercase names
69 * value: Redacted.make("Bearer ..."),
70 * });
71 * ```
72 *
73 * @see https://developers.cloudflare.com/security-center/
74 *
75 * @resource
76 * @product Vulnerability Scanner
77 * @category Application Security
78 */
79 export const VulnScannerCredentialSet = Resource<VulnScannerCredentialSet>(TypeId);
80
81 /**
82 * Returns true if the given value is a VulnScannerCredentialSet resource.
83 */
84 export const isVulnScannerCredentialSet = (value: unknown): value is VulnScannerCredentialSet =>
85 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
86
87 export const VulnScannerCredentialSetProvider = () =>
88 Provider.succeed(VulnScannerCredentialSet, {
89 stables: ["credentialSetId", "accountId"],
90
91 list: Effect.fn(function* () {
92 const { accountId } = yield* yield* CloudflareEnvironment;
93 return yield* vulnScanner.listCredentialSets.pages({ accountId }).pipe(
94 Stream.runCollect,
95 Effect.map((chunk) =>
96 Array.from(chunk).flatMap((page) =>
97 (page.result ?? []).map((set) => toAttributes(set, accountId)),
98 ),
99 ),
100 );
101 }),
102
103 diff: Effect.fn(function* ({ news, output }) {
104 const { accountId } = yield* yield* CloudflareEnvironment;
105 if (!isResolved(news)) return undefined;
106 if ((output?.accountId ?? accountId) !== accountId) {
107 return { action: "replace" } as const;
108 }
109 return undefined;
110 }),
111
112 read: Effect.fn(function* ({ id, output, olds }) {
113 const { accountId } = yield* yield* CloudflareEnvironment;
114 const acct = output?.accountId ?? accountId;
115
116 // Owned path: refresh by the persisted UUID.
117 if (output?.credentialSetId) {
118 const observed = yield* observeCredentialSet(acct, output.credentialSetId);
119 return observed ? toAttributes(observed, acct) : undefined;
120 }
121
122 // Cold read: match the deterministic physical name. Names carry no
123 // ownership markers, so gate takeover behind the adopt policy.
124 const name = yield* createSetName(id, olds?.name);
125 const match = yield* findCredentialSetByName(acct, name);
126 return match ? Unowned(toAttributes(match, acct)) : undefined;
127 }),
128
129 reconcile: Effect.fn(function* ({ id, news, output }) {
130 const { accountId } = yield* yield* CloudflareEnvironment;
131 const name = yield* createSetName(id, news.name);
132
133 // 1. Observe — cached UUID first, then deterministic name (recovers
134 // from a crash between create and state persistence).
135 let observed = output?.credentialSetId
136 ? yield* observeCredentialSet(output.accountId ?? accountId, output.credentialSetId)
137 : undefined;
138 if (!observed) {
139 observed = yield* findCredentialSetByName(accountId, name);
140 }
141
142 // 2. Ensure — create when missing.
143 if (!observed) {
144 const created = yield* vulnScanner.createCredentialSet({
145 accountId,
146 name,
147 });
148 return toAttributes(created, accountId);
149 }
150
151 // 3. Sync — the only mutable aspect is the name; PUT when it drifts.
152 if (observed.name !== name) {
153 const updated = yield* vulnScanner.updateCredentialSet({
154 accountId,
155 credentialSetId: observed.id,
156 name,
157 });
158 return toAttributes(updated, accountId);
159 }
160
161 // 4. Return.
162 return toAttributes(observed, accountId);
163 }),
164
165 delete: Effect.fn(function* ({ output }) {
166 yield* vulnScanner
167 .deleteCredentialSet({
168 accountId: output.accountId,
169 credentialSetId: output.credentialSetId,
170 })
171 .pipe(Effect.catchTag("CredentialSetNotFound", () => Effect.void));
172 }),
173 });
174
175 interface ObservedCredentialSet {
176 readonly id: string;
177 readonly name: string;
178 }
179
180 /**
181 * Read a credential set by id, mapping "gone" (`CredentialSetNotFound`,
182 * Cloudflare error code 14001) to `undefined`.
183 */
184 const observeCredentialSet = (accountId: string, credentialSetId: string) =>
185 vulnScanner
186 .getCredentialSet({ accountId, credentialSetId })
187 .pipe(Effect.catchTag("CredentialSetNotFound", () => Effect.undefined));
188
189 /**
190 * Find a credential set by exact name. Names are not unique on Cloudflare's
191 * side; if several match, pick the lexicographically smallest id for
192 * determinism.
193 */
194 const findCredentialSetByName = (accountId: string, name: string) =>
195 vulnScanner.listCredentialSets.items({ accountId }).pipe(
196 Stream.filter((s) => s.name === name),
197 Stream.runCollect,
198 Effect.map((chunk): ObservedCredentialSet | undefined =>
199 Array.from(chunk)
200 .sort((a, b) => a.id.localeCompare(b.id))
201 .at(0),
202 ),
203 );
204
205 const createSetName = (id: string, name: string | undefined) =>
206 Effect.gen(function* () {
207 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
208 });
209
210 const toAttributes = (
211 set: ObservedCredentialSet,
212 accountId: string,
213 ): VulnScannerCredentialSetAttributes => ({
214 credentialSetId: set.id,
215 accountId,
216 name: set.name,
217 });