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

main
ts 265 lines 9.5 KB
Raw
1 import * as inspector2 from "@distilled.cloud/aws/inspector2";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { AWSEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10
11 /**
12 * The Amazon Inspector scan types that can be enabled per account.
13 */
14 export type ResourceScanType = "EC2" | "ECR" | "LAMBDA" | "LAMBDA_CODE" | "CODE_REPOSITORY";
15
16 /**
17 * Raised when Inspector does not reach the requested scan state within the
18 * provider's bounded convergence budget.
19 */
20 export class Inspector2NotConverged extends Data.TaggedError("Inspector2NotConverged")<{
21 readonly accountId: string;
22 readonly expected: string;
23 readonly actual: Readonly<Record<string, string | undefined>>;
24 }> {}
25
26 export interface EnablerProps {
27 /**
28 * The resource scan types to enable for the account (e.g. `EC2`, `ECR`,
29 * `LAMBDA`). Types managed by this resource are disabled again on destroy.
30 */
31 resourceTypes: ResourceScanType[];
32 }
33
34 /** @resource */
35 export interface Enabler extends Resource<
36 "AWS.Inspector2.Enabler",
37 EnablerProps,
38 {
39 /** The account the enabler applies to. */
40 accountId: string;
41 /** The scan types currently enabled and managed by this resource. */
42 resourceTypes: string[];
43 /** The overall Inspector account status (`ENABLED` / `DISABLED` / ...). */
44 state: string | undefined;
45 },
46 never,
47 Providers
48 > {}
49
50 /**
51 * Amazon Inspector account enablement — an account/region singleton that turns
52 * on continuous vulnerability scanning for the selected resource types (EC2,
53 * ECR, Lambda). Inspector exposes no tagging, so ownership is tracked by the
54 * set of scan types this resource enabled; destroy only disables those types
55 * and leaves any the account had enabled out-of-band untouched.
56 *
57 * ### Enabling Inspector
58 * **Example:** Enable EC2, ECR, and Lambda scanning
59 * ```typescript
60 * const inspector = yield* Inspector2.Enabler("Inspector", {
61 * resourceTypes: ["EC2", "ECR", "LAMBDA"],
62 * });
63 * ```
64 */
65 const EnablerResource = Resource<Enabler>("AWS.Inspector2.Enabler");
66
67 export { EnablerResource as Enabler };
68
69 // The scan-type keys as they appear on the account's `resourceState`, mapped to
70 // their `EnableRequest` resource-type names.
71 const RESOURCE_STATE_KEYS = {
72 ec2: "EC2",
73 ecr: "ECR",
74 lambda: "LAMBDA",
75 lambdaCode: "LAMBDA_CODE",
76 codeRepository: "CODE_REPOSITORY",
77 } as const;
78
79 const TYPE_TO_STATE_KEY: Record<string, keyof typeof RESOURCE_STATE_KEYS> = {
80 EC2: "ec2",
81 ECR: "ecr",
82 LAMBDA: "lambda",
83 LAMBDA_CODE: "lambdaCode",
84 CODE_REPOSITORY: "codeRepository",
85 };
86
87 const statusOfType = (
88 resourceState: inspector2.ResourceState | undefined,
89 type: string,
90 ): string | undefined => {
91 const key = TYPE_TO_STATE_KEY[type];
92 if (!resourceState || !key) return undefined;
93 return resourceState[key]?.status;
94 };
95
96 const enabledTypes = (resourceState: inspector2.ResourceState | undefined): string[] => {
97 if (!resourceState) return [];
98 const out: string[] = [];
99 for (const key of Object.keys(RESOURCE_STATE_KEYS) as Array<keyof typeof RESOURCE_STATE_KEYS>) {
100 if (resourceState[key]?.status === "ENABLED") {
101 out.push(RESOURCE_STATE_KEYS[key]);
102 }
103 }
104 return out;
105 };
106
107 const statusesOf = (
108 resourceState: inspector2.ResourceState | undefined,
109 types: readonly string[],
110 ): Record<string, string | undefined> =>
111 Object.fromEntries(types.map((type) => [type, statusOfType(resourceState, type)]));
112
113 export const EnablerProvider = () =>
114 Provider.effect(
115 EnablerResource,
116 Effect.gen(function* () {
117 const getAccount = (accountId: string) =>
118 inspector2
119 .batchGetAccountStatus({ accountIds: [accountId] })
120 .pipe(Effect.map((r) => r.accounts?.[0]));
121
122 // Inspector enablement can remain transitional for several minutes.
123 // Keep the provider's wait bounded (~50s) and, critically, check the
124 // terminal value because Effect.repeat returns its last success when the
125 // repetition budget is exhausted even if `until` never became true.
126 const waitUntilEnabled = Effect.fn(function* (accountId: string, types: readonly string[]) {
127 const account = yield* getAccount(accountId).pipe(
128 Effect.repeat({
129 schedule: Schedule.spaced("5 seconds"),
130 until: (account) =>
131 types.every((t) => statusOfType(account?.resourceState, t) === "ENABLED"),
132 times: 10,
133 }),
134 );
135 if (!types.every((type) => statusOfType(account?.resourceState, type) === "ENABLED")) {
136 return yield* new Inspector2NotConverged({
137 accountId,
138 expected: "ENABLED",
139 actual: statusesOf(account?.resourceState, types),
140 });
141 }
142 return account;
143 });
144
145 const disableManagedTypes = Effect.fn(function* (
146 accountId: string,
147 types: readonly string[],
148 ) {
149 if (types.length === 0) return;
150
151 let account = yield* getAccount(accountId);
152 const enabling = types.filter(
153 (type) => statusOfType(account?.resourceState, type) === "ENABLING",
154 );
155 if (enabling.length > 0) {
156 yield* waitUntilEnabled(accountId, enabling);
157 account = yield* getAccount(accountId);
158 }
159
160 // DISABLING and DISABLED are already converging toward deletion. Only
161 // issue disable for types that are observably enabled.
162 const enabled = types.filter(
163 (type) => statusOfType(account?.resourceState, type) === "ENABLED",
164 );
165 if (enabled.length === 0) return;
166 yield* inspector2
167 .disable({ accountIds: [accountId], resourceTypes: enabled })
168 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
169 });
170
171 return {
172 read: Effect.fn(function* ({ output }) {
173 const accountId = output?.accountId ?? (yield* AWSEnvironment.current).accountId;
174 const account = yield* getAccount(accountId);
175 if (!account) return undefined;
176 const enabled = enabledTypes(account.resourceState);
177 const managed = output
178 ? output.resourceTypes.filter(
179 (type) => statusOfType(account.resourceState, type) !== "DISABLED",
180 )
181 : enabled;
182 if (managed.length === 0) return undefined;
183 const attrs = {
184 accountId,
185 resourceTypes: managed,
186 state: account.state?.status,
187 };
188 // Inspector has no tags. A live singleton without prior Alchemy
189 // state is foreign and must be explicitly adopted.
190 return output ? attrs : Unowned(attrs);
191 }),
192
193 // Inspector enablement is an account/region singleton keyed on the
194 // caller's account. Report the single account status.
195 list: () =>
196 Effect.gen(function* () {
197 const { accountId } = yield* AWSEnvironment.current;
198 const account = yield* getAccount(accountId);
199 const enabled = enabledTypes(account?.resourceState);
200 if (!account || enabled.length === 0) return [];
201 return [
202 {
203 accountId,
204 resourceTypes: enabled,
205 state: account.state?.status,
206 },
207 ];
208 }),
209
210 reconcile: Effect.fn(function* ({ news, output, session }) {
211 const { accountId } = yield* AWSEnvironment.current;
212 const desired: string[] = news.resourceTypes ?? [];
213
214 // 1. OBSERVE
215 const account = yield* getAccount(accountId);
216 const currentlyEnabled = enabledTypes(account?.resourceState);
217
218 // 2. ENSURE — enable any desired type not yet enabled.
219 const toEnable = desired.filter(
220 (type) =>
221 !currentlyEnabled.includes(type) &&
222 statusOfType(account?.resourceState, type) !== "ENABLING",
223 );
224 if (toEnable.length > 0) {
225 yield* inspector2.enable({
226 accountIds: [accountId],
227 resourceTypes: toEnable,
228 });
229 }
230
231 // Wait for the desired types to reach the terminal ENABLED state
232 // before returning — otherwise a follow-up destroy would be rejected
233 // with ENABLE_IN_PROGRESS.
234 if (desired.some((type) => !currentlyEnabled.includes(type))) {
235 yield* waitUntilEnabled(accountId, desired);
236 }
237
238 // 3. SYNC — disable any type we previously managed but no longer want.
239 // Disable teardown is slow (minutes); fire it and do not block, the
240 // account converges to the desired set asynchronously.
241 const previouslyManaged = output?.resourceTypes ?? [];
242 const noLongerManaged = previouslyManaged.filter((type) => !desired.includes(type));
243 yield* disableManagedTypes(accountId, noLongerManaged);
244
245 const final = yield* getAccount(accountId);
246 const managed = [
247 ...new Set([
248 ...previouslyManaged.filter((type) => desired.includes(type)),
249 ...toEnable,
250 ]),
251 ];
252 yield* session.note(accountId);
253 return {
254 accountId,
255 resourceTypes: managed,
256 state: final?.state?.status,
257 };
258 }),
259
260 delete: Effect.fn(function* ({ output }) {
261 yield* disableManagedTypes(output.accountId, output.resourceTypes);
262 }),
263 };
264 }),
265 );