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

main
ts 199 lines 7.24 KB
Raw
1 import * as guardduty from "@distilled.cloud/aws/guardduty";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { createInternalTags, diffTags, hasAlchemyTags, tagRecord } from "alchemy/Tags";
6 import * as Effect from "effect/Effect";
7 import { AWSEnvironment } from "../Environment.ts";
8 import type { Providers } from "../Providers.ts";
9
10 /**
11 * How frequently GuardDuty exports updated findings.
12 */
13 export type FindingPublishingFrequency = "FIFTEEN_MINUTES" | "ONE_HOUR" | "SIX_HOURS";
14
15 export interface DetectorProps {
16 /**
17 * Whether the detector is enabled. A disabled detector stops analyzing data
18 * sources but is not deleted.
19 * @default true
20 */
21 enable?: boolean;
22
23 /**
24 * How frequently GuardDuty publishes updated findings to CloudWatch Events.
25 * @default "SIX_HOURS"
26 */
27 findingPublishingFrequency?: FindingPublishingFrequency;
28
29 /**
30 * Tags applied to the detector. Alchemy ownership tags are merged in
31 * automatically so the detector can be recognized on subsequent runs.
32 */
33 tags?: Record<string, string>;
34 }
35
36 /** @resource */
37 export interface Detector extends Resource<
38 "AWS.GuardDuty.Detector",
39 DetectorProps,
40 {
41 /** The auto-generated detector ID (unique per account/region). */
42 detectorId: string;
43 /** ARN of the detector — the IAM resource for detector-scoped actions. */
44 detectorArn: string;
45 /** Current status of the detector (`ENABLED` / `DISABLED`). */
46 status: string | undefined;
47 /** The effective finding-publishing frequency. */
48 findingPublishingFrequency: string | undefined;
49 },
50 never,
51 Providers
52 > {}
53
54 /**
55 * A GuardDuty detector — the account/region singleton that enables Amazon
56 * GuardDuty threat detection. Only one detector can exist per region, so this
57 * resource is a capture-and-restore singleton: adopting a pre-existing detector
58 * that Alchemy did not create requires `--adopt`.
59 *
60 * ### Enabling GuardDuty
61 * **Example:** Enable with default settings
62 * ```typescript
63 * const detector = yield* GuardDuty.Detector("Detector", {});
64 * ```
65 *
66 * **Example:** Frequent finding publishing
67 * ```typescript
68 * const detector = yield* GuardDuty.Detector("Detector", {
69 * enable: true,
70 * findingPublishingFrequency: "FIFTEEN_MINUTES",
71 * tags: { team: "security" },
72 * });
73 * ```
74 */
75 const DetectorResource = Resource<Detector>("AWS.GuardDuty.Detector");
76
77 export { DetectorResource as Detector };
78
79 export const detectorArn = (region: string, accountId: string, detectorId: string) =>
80 `arn:aws:guardduty:${region}:${accountId}:detector/${detectorId}`;
81
82 const buildAttrs = Effect.fn(function* (detectorId: string, d: guardduty.GetDetectorResponse) {
83 const { accountId, region } = yield* AWSEnvironment.current;
84 return {
85 detectorId,
86 detectorArn: detectorArn(region, accountId, detectorId),
87 status: d.Status,
88 findingPublishingFrequency: d.FindingPublishingFrequency,
89 };
90 });
91
92 export const DetectorProvider = () =>
93 Provider.effect(
94 DetectorResource,
95 Effect.gen(function* () {
96 // Resolve the first (only) detector in the current region, if any.
97 const firstDetectorId = guardduty
98 .listDetectors({})
99 .pipe(Effect.map((r) => r.DetectorIds?.[0]));
100
101 const getDetector = (detectorId: string) =>
102 guardduty
103 .getDetector({ DetectorId: detectorId })
104 .pipe(Effect.catchTag("BadRequestException", () => Effect.undefined));
105
106 return {
107 read: Effect.fn(function* ({ id, output }) {
108 const detectorId = output?.detectorId ?? (yield* firstDetectorId);
109 if (!detectorId) return undefined;
110 const d = yield* getDetector(detectorId);
111 if (!d) return undefined;
112 const attrs = yield* buildAttrs(detectorId, d);
113 return (yield* hasAlchemyTags(id, d.Tags)) ? attrs : Unowned(attrs);
114 }),
115
116 // GuardDuty allows at most one detector per account/region. Enumerate
117 // every detector and hydrate its full attributes.
118 list: () =>
119 Effect.gen(function* () {
120 const { DetectorIds } = yield* guardduty.listDetectors({});
121 const out: {
122 detectorId: string;
123 detectorArn: string;
124 status: string | undefined;
125 findingPublishingFrequency: string | undefined;
126 }[] = [];
127 for (const detectorId of DetectorIds ?? []) {
128 const d = yield* getDetector(detectorId);
129 if (d) out.push(yield* buildAttrs(detectorId, d));
130 }
131 return out;
132 }),
133
134 reconcile: Effect.fn(function* ({ id, news = {}, output, session }) {
135 const { accountId, region } = yield* AWSEnvironment.current;
136 const internalTags = yield* createInternalTags(id);
137 const desiredTags = { ...news.tags, ...internalTags };
138 const desiredEnable = news.enable ?? true;
139
140 // 1. OBSERVE — cloud state is authoritative; output is only an id cache.
141 let detectorId = output?.detectorId ?? (yield* firstDetectorId);
142 let live = detectorId ? yield* getDetector(detectorId) : undefined;
143
144 if (!detectorId || !live) {
145 // 2. ENSURE — create the detector with tags applied inline.
146 const created = yield* guardduty.createDetector({
147 Enable: desiredEnable,
148 FindingPublishingFrequency: news.findingPublishingFrequency,
149 Tags: desiredTags,
150 });
151 detectorId = created.DetectorId!;
152 } else {
153 // 3. SYNC settings — observed ↔ desired.
154 const observedEnabled = live.Status === "ENABLED";
155 const settingsChanged =
156 observedEnabled !== desiredEnable ||
157 (news.findingPublishingFrequency !== undefined &&
158 news.findingPublishingFrequency !== live.FindingPublishingFrequency);
159 if (settingsChanged) {
160 yield* guardduty.updateDetector({
161 DetectorId: detectorId,
162 Enable: desiredEnable,
163 FindingPublishingFrequency: news.findingPublishingFrequency,
164 });
165 }
166
167 // 3b. SYNC tags — diff against OBSERVED cloud tags.
168 const { upsert, removed } = diffTags(tagRecord(live.Tags), desiredTags);
169 const arn = detectorArn(region, accountId, detectorId);
170 if (upsert.length > 0) {
171 yield* guardduty.tagResource({
172 ResourceArn: arn,
173 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
174 });
175 }
176 if (removed.length > 0) {
177 yield* guardduty.untagResource({
178 ResourceArn: arn,
179 TagKeys: removed,
180 });
181 }
182 }
183
184 // 4. RETURN fresh attributes.
185 const final = yield* guardduty.getDetector({
186 DetectorId: detectorId,
187 });
188 yield* session.note(detectorId);
189 return yield* buildAttrs(detectorId, final);
190 }),
191
192 delete: Effect.fn(function* ({ output }) {
193 yield* guardduty
194 .deleteDetector({ DetectorId: output.detectorId })
195 .pipe(Effect.catchTag("BadRequestException", () => Effect.void));
196 }),
197 };
198 }),
199 );