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

main
ts 170 lines 5.92 KB
Raw
1 import * as macie2 from "@distilled.cloud/aws/macie2";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import { AWSEnvironment } from "../Environment.ts";
7 import type { Providers } from "../Providers.ts";
8
9 /**
10 * How frequently Amazon Macie publishes updated policy findings.
11 */
12 export type FindingPublishingFrequency = "FIFTEEN_MINUTES" | "ONE_HOUR" | "SIX_HOURS";
13
14 /**
15 * The Macie enablement status. `ENABLED` runs Macie; `PAUSED` suspends it
16 * without disabling the account entirely.
17 */
18 export type MacieStatus = "PAUSED" | "ENABLED";
19
20 export interface SessionProps {
21 /**
22 * Whether Macie is enabled (`ENABLED`) or suspended (`PAUSED`) for the
23 * account. A paused session stops all Macie activity but keeps the account
24 * enrolled.
25 * @default "ENABLED"
26 */
27 status?: MacieStatus;
28
29 /**
30 * How frequently Macie publishes updated policy findings to EventBridge and
31 * Security Hub.
32 * @default "SIX_HOURS"
33 */
34 findingPublishingFrequency?: FindingPublishingFrequency;
35 }
36
37 /** @resource */
38 export interface Session extends Resource<
39 "AWS.Macie2.Session",
40 SessionProps,
41 {
42 /** The account the Macie session belongs to. */
43 accountId: string;
44 /** Current Macie status (`ENABLED` / `PAUSED`). */
45 status: string | undefined;
46 /** The effective finding-publishing frequency. */
47 findingPublishingFrequency: string | undefined;
48 /** ARN of the Macie service-linked role. */
49 serviceRole: string | undefined;
50 /** ISO timestamp of when the Macie session was created. */
51 createdAt: string | undefined;
52 },
53 never,
54 Providers
55 > {}
56
57 /**
58 * The Amazon Macie session — the account/region singleton that enables Macie
59 * data-security scanning. Only one session can exist per region, so this is a
60 * capture-and-restore singleton: Macie exposes no session tags, so ownership is
61 * tracked by Alchemy state. Adopting a session that Alchemy did not create
62 * requires `--adopt`, and destroy disables Macie for the account.
63 *
64 * ### Enabling Macie
65 * **Example:** Enable Macie
66 * ```typescript
67 * const macie = yield* Macie2.Session("Macie", {});
68 * ```
69 *
70 * **Example:** Enable with frequent findings and pause later
71 * ```typescript
72 * const macie = yield* Macie2.Session("Macie", {
73 * status: "ENABLED",
74 * findingPublishingFrequency: "FIFTEEN_MINUTES",
75 * });
76 * ```
77 */
78 const SessionResource = Resource<Session>("AWS.Macie2.Session");
79
80 export { SessionResource as Session };
81
82 // `getMacieSession` throws `AccessDeniedException` ("Macie is not enabled")
83 // when the account has no session and `ResourceNotFoundException` transiently
84 // right after enablement — both mean "no session", so collapse to `undefined`.
85 const getSession = macie2.getMacieSession({}).pipe(
86 Effect.map((s) => s as macie2.GetMacieSessionResponse | undefined),
87 Effect.catchTags({
88 AccessDeniedException: () => Effect.undefined,
89 ResourceNotFoundException: () => Effect.undefined,
90 }),
91 );
92
93 const buildAttrs = (accountId: string, s: macie2.GetMacieSessionResponse) => ({
94 accountId,
95 status: s.status,
96 findingPublishingFrequency: s.findingPublishingFrequency,
97 serviceRole: s.serviceRole,
98 createdAt: s.createdAt?.toISOString(),
99 });
100
101 export const SessionProvider = () =>
102 Provider.effect(
103 SessionResource,
104 Effect.gen(function* () {
105 return {
106 read: Effect.fn(function* ({ output }) {
107 const session = yield* getSession;
108 if (!session) return undefined;
109 const accountId = output?.accountId ?? (yield* AWSEnvironment.current).accountId;
110 const attrs = buildAttrs(accountId, session);
111 // Macie has no session-level tags, so ownership cannot be verified
112 // from the cloud. If we have no prior state (`output` absent) but a
113 // session already exists, treat it as foreign and gate adoption.
114 return output ? attrs : Unowned(attrs);
115 }),
116
117 // Account/region singleton — report the single session, if any.
118 list: () =>
119 Effect.gen(function* () {
120 const session = yield* getSession;
121 if (!session) return [];
122 const { accountId } = yield* AWSEnvironment.current;
123 return [buildAttrs(accountId, session)];
124 }),
125
126 reconcile: Effect.fn(function* ({ news = {}, session }) {
127 const { accountId } = yield* AWSEnvironment.current;
128 const desiredStatus = news.status ?? "ENABLED";
129
130 // 1. OBSERVE — cloud state is authoritative.
131 let live = yield* getSession;
132
133 // 2. ENSURE — enable Macie if there is no session.
134 if (!live) {
135 yield* macie2.enableMacie({
136 status: desiredStatus,
137 findingPublishingFrequency: news.findingPublishingFrequency,
138 });
139 live = yield* macie2.getMacieSession({});
140 } else {
141 // 3. SYNC — observed ↔ desired status + finding frequency.
142 const statusChanged = live.status !== desiredStatus;
143 const freqChanged =
144 news.findingPublishingFrequency !== undefined &&
145 news.findingPublishingFrequency !== live.findingPublishingFrequency;
146 if (statusChanged || freqChanged) {
147 yield* macie2.updateMacieSession({
148 status: desiredStatus,
149 findingPublishingFrequency: news.findingPublishingFrequency,
150 });
151 }
152 }
153
154 // 4. RETURN fresh attributes.
155 const final = yield* macie2.getMacieSession({});
156 yield* session.note(accountId);
157 return buildAttrs(accountId, final);
158 }),
159
160 delete: Effect.fn(function* () {
161 yield* macie2.disableMacie({}).pipe(
162 Effect.catchTags({
163 AccessDeniedException: () => Effect.void,
164 ResourceNotFoundException: () => Effect.void,
165 }),
166 );
167 }),
168 };
169 }),
170 );