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

main
ts 193 lines 6.55 KB
Raw
1 import * as securityhub from "@distilled.cloud/aws/securityhub";
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 * Which finding format Security Hub generates for controls.
12 */
13 export type ControlFindingGenerator = "STANDARD_CONTROL" | "SECURITY_CONTROL";
14
15 export interface HubProps {
16 /**
17 * Whether to enable the default security standards (AWS Foundational Security
18 * Best Practices, CIS) when Security Hub is first enabled. Only takes effect
19 * on the initial enablement.
20 * @default true
21 */
22 enableDefaultStandards?: boolean;
23
24 /**
25 * Whether Security Hub automatically enables new controls when they are added
26 * to enabled standards.
27 */
28 autoEnableControls?: boolean;
29
30 /**
31 * Whether to generate `STANDARD_CONTROL` or `SECURITY_CONTROL` findings.
32 */
33 controlFindingGenerator?: ControlFindingGenerator;
34
35 /**
36 * Tags applied to the Hub. Alchemy ownership tags are merged in automatically.
37 */
38 tags?: Record<string, string>;
39 }
40
41 /** @resource */
42 export interface Hub extends Resource<
43 "AWS.SecurityHub.Hub",
44 HubProps,
45 {
46 /** ARN of the Security Hub Hub resource. */
47 hubArn: string;
48 /** When Security Hub was enabled for the account. */
49 subscribedAt: string | undefined;
50 /** Whether new controls are auto-enabled. */
51 autoEnableControls: boolean | undefined;
52 /** The active control finding generator. */
53 controlFindingGenerator: string | undefined;
54 },
55 never,
56 Providers
57 > {}
58
59 /**
60 * The Security Hub Hub — the account/region singleton that enables AWS Security
61 * Hub. Only one Hub can exist per region, so this is a capture-and-restore
62 * singleton: adopting a pre-existing Hub that Alchemy did not create requires
63 * `--adopt`.
64 *
65 * ### Enabling Security Hub
66 * **Example:** Enable with default standards
67 * ```typescript
68 * const hub = yield* SecurityHub.Hub("Hub", {});
69 * ```
70 *
71 * **Example:** Enable without default standards, auto-enable controls
72 * ```typescript
73 * const hub = yield* SecurityHub.Hub("Hub", {
74 * enableDefaultStandards: false,
75 * autoEnableControls: true,
76 * controlFindingGenerator: "SECURITY_CONTROL",
77 * tags: { team: "security" },
78 * });
79 * ```
80 */
81 const HubResource = Resource<Hub>("AWS.SecurityHub.Hub");
82
83 export { HubResource as Hub };
84
85 const hubArnFallback = (region: string, accountId: string) =>
86 `arn:aws:securityhub:${region}:${accountId}:hub/default`;
87
88 const buildAttrs = (hub: securityhub.DescribeHubResponse) => ({
89 hubArn: hub.HubArn!,
90 subscribedAt: hub.SubscribedAt,
91 autoEnableControls: hub.AutoEnableControls,
92 controlFindingGenerator: hub.ControlFindingGenerator,
93 });
94
95 // `describeHub` throws `InvalidAccessException` when the account is not
96 // subscribed and `ResourceNotFoundException` transiently right after enable —
97 // both mean "no Hub", so collapse them to `undefined`.
98 const describeHub = securityhub.describeHub({}).pipe(
99 Effect.catchTags({
100 InvalidAccessException: () => Effect.undefined,
101 ResourceNotFoundException: () => Effect.undefined,
102 }),
103 );
104
105 export const HubProvider = () =>
106 Provider.effect(
107 HubResource,
108 Effect.gen(function* () {
109 const readTags = (arn: string) =>
110 securityhub.listTagsForResource({ ResourceArn: arn }).pipe(
111 Effect.map((r) => tagRecord(r.Tags)),
112 Effect.orElseSucceed(() => ({})),
113 );
114
115 return {
116 read: Effect.fn(function* ({ id }) {
117 const hub = yield* describeHub;
118 if (!hub) return undefined;
119 const attrs = buildAttrs(hub);
120 const tags = yield* readTags(attrs.hubArn);
121 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
122 }),
123
124 // Security Hub is an account/region singleton — `describeHub` returns
125 // the single Hub or throws when unsubscribed.
126 list: () => describeHub.pipe(Effect.map((hub) => (hub ? [buildAttrs(hub)] : []))),
127
128 reconcile: Effect.fn(function* ({ id, news = {}, session }) {
129 const { accountId, region } = yield* AWSEnvironment.current;
130 const internalTags = yield* createInternalTags(id);
131 const desiredTags = { ...news.tags, ...internalTags };
132
133 // 1. OBSERVE
134 let hub = yield* describeHub;
135
136 // 2. ENSURE — enable Security Hub if not already subscribed.
137 if (!hub) {
138 yield* securityhub.enableSecurityHub({
139 Tags: desiredTags,
140 EnableDefaultStandards: news.enableDefaultStandards ?? true,
141 ControlFindingGenerator: news.controlFindingGenerator,
142 });
143 hub = yield* securityhub.describeHub({});
144 }
145
146 const arn = hub.HubArn ?? hubArnFallback(region, accountId);
147
148 // 3. SYNC configuration — observed ↔ desired.
149 const configChanged =
150 (news.autoEnableControls !== undefined &&
151 news.autoEnableControls !== hub.AutoEnableControls) ||
152 (news.controlFindingGenerator !== undefined &&
153 news.controlFindingGenerator !== hub.ControlFindingGenerator);
154 if (configChanged) {
155 yield* securityhub.updateSecurityHubConfiguration({
156 AutoEnableControls: news.autoEnableControls,
157 ControlFindingGenerator: news.controlFindingGenerator,
158 });
159 }
160
161 // 3b. SYNC tags — diff against OBSERVED cloud tags.
162 const currentTags = yield* readTags(arn);
163 const { upsert, removed } = diffTags(currentTags, desiredTags);
164 if (upsert.length > 0) {
165 yield* securityhub.tagResource({
166 ResourceArn: arn,
167 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
168 });
169 }
170 if (removed.length > 0) {
171 yield* securityhub.untagResource({
172 ResourceArn: arn,
173 TagKeys: removed,
174 });
175 }
176
177 // 4. RETURN fresh attributes.
178 const final = yield* securityhub.describeHub({});
179 yield* session.note(arn);
180 return buildAttrs(final);
181 }),
182
183 delete: Effect.fn(function* () {
184 yield* securityhub.disableSecurityHub({}).pipe(
185 Effect.catchTags({
186 ResourceNotFoundException: () => Effect.void,
187 InvalidAccessException: () => Effect.void,
188 }),
189 );
190 }),
191 };
192 }),
193 );