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

main
ts 256 lines 9.08 KB
Raw
1 import * as macie2 from "@distilled.cloud/aws/macie2";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, diffTags, hasAlchemyTags, tagRecord } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import { retryThroughEnablement } from "./common.ts";
12
13 export interface CustomDataIdentifierProps {
14 /**
15 * Custom name for the identifier (1-128 characters). Must be unique per
16 * account. If omitted, a unique name is generated from the app/stage/logical
17 * ID. Changing this replaces the identifier — custom data identifiers are
18 * immutable once created.
19 */
20 name?: string;
21
22 /**
23 * Custom description of the identifier (up to 512 characters). Changing this
24 * replaces the identifier.
25 */
26 description?: string;
27
28 /**
29 * The regular expression that defines the text pattern to match (up to 512
30 * characters). Changing this replaces the identifier.
31 */
32 regex: string;
33
34 /**
35 * Words that must be in proximity of a pattern match for Macie to report it
36 * (up to 50 keywords, each 3-90 UTF-8 characters). Changing this replaces
37 * the identifier.
38 */
39 keywords?: string[];
40
41 /**
42 * Words to exclude from the results — a match containing one of these is
43 * ignored (up to 10 entries, each 4-90 UTF-8 characters). Changing this
44 * replaces the identifier.
45 */
46 ignoreWords?: string[];
47
48 /**
49 * The maximum number of characters between the end of a keyword and the end
50 * of the matched text (1-300). Changing this replaces the identifier.
51 * @default 50
52 */
53 maximumMatchDistance?: number;
54
55 /**
56 * Severity to assign findings based on the number of occurrences of matched
57 * text. Changing this replaces the identifier.
58 */
59 severityLevels?: macie2.SeverityLevel[];
60
61 /**
62 * Tags applied to the identifier. Alchemy ownership tags are merged in
63 * automatically.
64 */
65 tags?: Record<string, string>;
66 }
67
68 /** @resource */
69 export interface CustomDataIdentifier extends Resource<
70 "AWS.Macie2.CustomDataIdentifier",
71 CustomDataIdentifierProps,
72 {
73 /** Generated custom data identifier ID. */
74 id: string;
75 /** ARN of the custom data identifier. */
76 arn: string;
77 /** The resolved identifier name. */
78 name: string;
79 },
80 never,
81 Providers
82 > {}
83
84 /**
85 * An Amazon Macie custom data identifier — a regex-based detection criterion
86 * (with optional keywords, ignore words, and severity thresholds) that
87 * classification jobs and automated discovery use to detect organization-
88 * specific sensitive data. Requires Macie to be enabled for the account (see
89 * `Macie2.Session`). Definitions are immutable: any change other than tags
90 * replaces the identifier. Destroy soft-deletes it.
91 *
92 * ### Creating a custom data identifier
93 * **Example:** Employee-id detector
94 * ```typescript
95 * const identifier = yield* Macie2.CustomDataIdentifier("EmployeeId", {
96 * regex: "EMP-[0-9]{8}",
97 * description: "Internal employee id format",
98 * });
99 * ```
100 *
101 * **Example:** Keyword-scoped detector with severity thresholds
102 * ```typescript
103 * const identifier = yield* Macie2.CustomDataIdentifier("AccountNumber", {
104 * regex: "[0-9]{12}",
105 * keywords: ["account number", "acct no"],
106 * maximumMatchDistance: 30,
107 * severityLevels: [
108 * { occurrencesThreshold: 1, severity: "LOW" },
109 * { occurrencesThreshold: 25, severity: "HIGH" },
110 * ],
111 * });
112 * ```
113 */
114 const CustomDataIdentifierResource = Resource<CustomDataIdentifier>(
115 "AWS.Macie2.CustomDataIdentifier",
116 );
117
118 export { CustomDataIdentifierResource as CustomDataIdentifier };
119
120 const createName = (id: string, props: Partial<CustomDataIdentifierProps>) =>
121 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 128 });
122
123 // The whole definition is immutable — any change replaces.
124 const fingerprint = (props: Partial<CustomDataIdentifierProps>) =>
125 JSON.stringify({
126 description: props.description,
127 regex: props.regex,
128 keywords: props.keywords ?? [],
129 ignoreWords: props.ignoreWords ?? [],
130 maximumMatchDistance: props.maximumMatchDistance,
131 severityLevels: props.severityLevels ?? [],
132 });
133
134 const buildIdentifierAttrs = (id: string, live: macie2.GetCustomDataIdentifierResponse) => ({
135 id,
136 arn: live.arn!,
137 name: live.name!,
138 });
139
140 export const CustomDataIdentifierProvider = () =>
141 Provider.effect(
142 CustomDataIdentifierResource,
143 Effect.gen(function* () {
144 const getIdentifier = (id: string) =>
145 macie2.getCustomDataIdentifier({ id }).pipe(
146 // Deleting is a soft delete — a deleted identifier still answers,
147 // flagged `deleted: true`. Treat it (and a disabled Macie session)
148 // as gone.
149 Effect.map((d) => (d.deleted ? undefined : d)),
150 Effect.catchTags({
151 ResourceNotFoundException: () => Effect.undefined,
152 AccessDeniedException: () => Effect.undefined,
153 }),
154 );
155
156 return {
157 stables: ["id", "arn", "name"],
158
159 read: Effect.fn(function* ({ id, output }) {
160 if (!output?.id) return undefined;
161 const live = yield* getIdentifier(output.id);
162 if (!live) return undefined;
163 const attrs = buildIdentifierAttrs(output.id, live);
164 return (yield* hasAlchemyTags(id, live.tags)) ? attrs : Unowned(attrs);
165 }),
166
167 list: () =>
168 Effect.gen(function* () {
169 const pages = yield* macie2.listCustomDataIdentifiers.pages({}).pipe(
170 Stream.runCollect,
171 Effect.catchTag("AccessDeniedException", () => Effect.succeed([])),
172 );
173 const out: CustomDataIdentifier["Attributes"][] = [];
174 for (const page of pages) {
175 for (const summary of page.items ?? []) {
176 const live = yield* getIdentifier(summary.id!);
177 if (live) out.push(buildIdentifierAttrs(summary.id!, live));
178 }
179 }
180 return out;
181 }),
182
183 diff: Effect.fn(function* ({ id, news, olds = {} }) {
184 if (!isResolved(news)) return undefined;
185 const oldName = yield* createName(id, olds);
186 const newName = yield* createName(id, news);
187 if (oldName !== newName) return { action: "replace" } as const;
188 if (fingerprint(olds) !== fingerprint(news)) {
189 return { action: "replace" } as const;
190 }
191 // The definition is immutable; only tags mutate in place.
192 return undefined;
193 }),
194
195 reconcile: Effect.fn(function* ({ id, news, output, session }) {
196 const internalTags = yield* createInternalTags(id);
197 const desiredTags = { ...news.tags, ...internalTags };
198 const name = output?.name ?? (yield* createName(id, news));
199
200 // 1. OBSERVE — cloud state is authoritative; output caches the id.
201 let identifierId = output?.id;
202 let live = identifierId ? yield* getIdentifier(identifierId) : undefined;
203
204 if (!live || identifierId === undefined) {
205 // 2. ENSURE — create the identifier (retry through enablement lag).
206 const created = yield* retryThroughEnablement(
207 macie2.createCustomDataIdentifier({
208 name,
209 description: news.description,
210 regex: news.regex,
211 keywords: news.keywords,
212 ignoreWords: news.ignoreWords,
213 maximumMatchDistance: news.maximumMatchDistance,
214 severityLevels: news.severityLevels,
215 tags: desiredTags,
216 }),
217 );
218 identifierId = created.customDataIdentifierId!;
219 } else {
220 // 3. SYNC tags — the definition is immutable; only tags mutate.
221 const { upsert, removed } = diffTags(tagRecord(live.tags), desiredTags);
222 if (upsert.length > 0) {
223 yield* macie2.tagResource({
224 resourceArn: live.arn!,
225 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
226 });
227 }
228 if (removed.length > 0) {
229 yield* macie2.untagResource({
230 resourceArn: live.arn!,
231 tagKeys: removed,
232 });
233 }
234 }
235
236 // 4. RETURN fresh attributes.
237 const final = yield* macie2.getCustomDataIdentifier({
238 id: identifierId,
239 });
240 yield* session.note(identifierId);
241 return buildIdentifierAttrs(identifierId, final);
242 }),
243
244 delete: Effect.fn(function* ({ output }) {
245 // Idempotent soft delete — the identifier may already be gone, or
246 // Macie may already be disabled for the account.
247 yield* macie2.deleteCustomDataIdentifier({ id: output.id }).pipe(
248 Effect.catchTags({
249 ResourceNotFoundException: () => Effect.void,
250 AccessDeniedException: () => Effect.void,
251 }),
252 );
253 }),
254 };
255 }),
256 );