@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 190 lines 6.53 KB
Raw
1 import * as securityhub from "@distilled.cloud/aws/securityhub";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Stream from "effect/Stream";
7 import type { Providers } from "../Providers.ts";
8
9 export interface InsightProps {
10 /**
11 * Name of the insight. If omitted, a unique name is generated. Updatable
12 * in place.
13 */
14 name?: string;
15
16 /**
17 * The finding filters the insight aggregates over, e.g.
18 * `{ SeverityLabel: [{ Value: "CRITICAL", Comparison: "EQUALS" }] }`.
19 * Updatable in place.
20 */
21 filters: securityhub.AwsSecurityFindingFilters;
22
23 /**
24 * The finding attribute results are grouped by, e.g. `ResourceId`,
25 * `SeverityLabel`, `AwsAccountId`. Updatable in place.
26 */
27 groupByAttribute: string;
28 }
29
30 /** @resource */
31 export interface Insight extends Resource<
32 "AWS.SecurityHub.Insight",
33 InsightProps,
34 {
35 /** ARN of the insight (its identity). */
36 insightArn: string;
37 /** Name of the insight. */
38 name: string;
39 /** The attribute results are grouped by. */
40 groupByAttribute: string;
41 },
42 never,
43 Providers
44 > {}
45
46 /**
47 * A Security Hub custom insight — a saved finding query grouped by an
48 * attribute. Read its aggregated results at runtime with the
49 * {@link GetInsightResults} binding.
50 *
51 * ### Creating an Insight
52 * **Example:** Critical Findings by Resource
53 * ```typescript
54 * const insight = yield* AWS.SecurityHub.Insight("CriticalByResource", {
55 * filters: {
56 * SeverityLabel: [{ Value: "CRITICAL", Comparison: "EQUALS" }],
57 * RecordState: [{ Value: "ACTIVE", Comparison: "EQUALS" }],
58 * },
59 * groupByAttribute: "ResourceId",
60 * });
61 * ```
62 *
63 * **Example:** Read Insight Results at Runtime
64 * ```typescript
65 * const getInsightResults = yield* AWS.SecurityHub.GetInsightResults();
66 * const { InsightResults } = yield* getInsightResults({
67 * InsightArn: insight.insightArn,
68 * });
69 * ```
70 */
71 const InsightResource = Resource<Insight>("AWS.SecurityHub.Insight");
72
73 export { InsightResource as Insight };
74
75 export const InsightProvider = () =>
76 Provider.effect(
77 InsightResource,
78 Effect.gen(function* () {
79 const toName = (id: string, props: { name?: string }) =>
80 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 128 });
81
82 const getInsight = (arn: string) =>
83 securityhub.getInsights({ InsightArns: [arn] }).pipe(
84 Effect.map((r) => r.Insights?.[0]),
85 Effect.catchTags({
86 ResourceNotFoundException: () => Effect.undefined,
87 // The whole hub may be disabled — the insight is gone too.
88 InvalidAccessException: () => Effect.undefined,
89 // Security Hub reports an unknown insight ARN as invalid input.
90 InvalidInputException: () => Effect.undefined,
91 }),
92 );
93
94 const listInsights = securityhub.getInsights.pages({}).pipe(
95 Stream.runCollect,
96 Effect.map((pages) => Array.from(pages).flatMap((page) => page.Insights ?? [])),
97 Effect.catchTag("InvalidAccessException", () =>
98 Effect.succeed([] as securityhub.Insight[]),
99 ),
100 );
101
102 const buildAttrs = (i: securityhub.Insight) => ({
103 insightArn: i.InsightArn!,
104 name: i.Name ?? "",
105 groupByAttribute: i.GroupByAttribute ?? "",
106 });
107
108 return {
109 stables: ["insightArn"],
110 read: Effect.fn(function* ({ id, olds, output }) {
111 if (output?.insightArn) {
112 const live = yield* getInsight(output.insightArn);
113 return live ? buildAttrs(live) : undefined;
114 }
115 // No prior state — find by (deterministic) name. Insights cannot be
116 // tagged; the generated name embeds the app/stage physical-name
117 // hash, so a match is ours.
118 const name = yield* toName(id, olds ?? {});
119 const all = yield* listInsights;
120 const match = all.find((i) => i.Name === name);
121 return match ? buildAttrs(match) : undefined;
122 }),
123 list: () => listInsights.pipe(Effect.map((all) => all.map(buildAttrs))),
124 reconcile: Effect.fn(function* ({ id, news, output, session }) {
125 const name = yield* toName(id, news);
126
127 // 1. OBSERVE — by cached ARN first, then by name.
128 let live: securityhub.Insight | undefined = output?.insightArn
129 ? yield* getInsight(output.insightArn)
130 : undefined;
131 if (!live) {
132 const all = yield* listInsights;
133 live = all.find((i) => i.Name === name);
134 }
135
136 let final: securityhub.Insight;
137 if (!live) {
138 // 2. ENSURE.
139 const { InsightArn } = yield* securityhub.createInsight({
140 Name: name,
141 Filters: news.filters,
142 GroupByAttribute: news.groupByAttribute,
143 });
144 // The read-after-create may lag — fall back to the desired state.
145 final = (yield* getInsight(InsightArn)) ?? {
146 InsightArn,
147 Name: name,
148 Filters: news.filters,
149 GroupByAttribute: news.groupByAttribute,
150 };
151 } else if (
152 live.Name !== name ||
153 live.GroupByAttribute !== news.groupByAttribute ||
154 JSON.stringify(live.Filters) !== JSON.stringify(news.filters)
155 ) {
156 // 3. SYNC — observed ↔ desired.
157 const arn = live.InsightArn!;
158 yield* securityhub.updateInsight({
159 InsightArn: arn,
160 Name: name,
161 Filters: news.filters,
162 GroupByAttribute: news.groupByAttribute,
163 });
164 final = (yield* getInsight(arn)) ?? {
165 InsightArn: arn,
166 Name: name,
167 Filters: news.filters,
168 GroupByAttribute: news.groupByAttribute,
169 };
170 } else {
171 final = live;
172 }
173
174 // 4. RETURN fresh attributes.
175 yield* session.note(final.InsightArn!);
176 return buildAttrs(final);
177 }),
178 delete: Effect.fn(function* ({ output }) {
179 // Idempotent — the insight (or the whole hub) may already be gone.
180 yield* securityhub.deleteInsight({ InsightArn: output.insightArn }).pipe(
181 Effect.catchTags({
182 ResourceNotFoundException: () => Effect.void,
183 InvalidAccessException: () => Effect.void,
184 InvalidInputException: () => Effect.void,
185 }),
186 );
187 }),
188 };
189 }),
190 );