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

main
ts 224 lines 8.23 KB
Raw
1 import * as frauddetector from "@distilled.cloud/aws/frauddetector";
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, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Redacted from "effect/Redacted";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import { readFraudDetectorTags, syncFraudDetectorTags } from "./internal.ts";
13
14 export interface ListProps {
15 /**
16 * Name of the list. If omitted, a unique lowercase name is generated from
17 * the app, stage, and logical ID. Changing the name replaces the list.
18 */
19 name?: string;
20 /**
21 * Human-readable description. This is an in-place update.
22 */
23 description?: string;
24 /**
25 * The variable type of the list's elements (e.g. `IP_ADDRESS`,
26 * `EMAIL_ADDRESS`). Fraud Detector only allows setting the variable type
27 * once — changing an already-set variable type replaces the list.
28 */
29 variableType?: string;
30 /**
31 * The elements of the list. Reconcile converges the live list to exactly
32 * this set (a `REPLACE` update); elements appended out-of-band (e.g. via the
33 * `UpdateList` runtime binding) are removed on the next deploy unless they
34 * are added here.
35 *
36 * @default []
37 */
38 elements?: string[];
39 /**
40 * User-defined tags for the list.
41 */
42 tags?: Record<string, string>;
43 }
44
45 export interface List extends Resource<
46 "AWS.FraudDetector.List",
47 ListProps,
48 {
49 /** The name of the list. */
50 name: string;
51 /** The ARN of the list. */
52 arn: string;
53 },
54 never,
55 Providers
56 > {}
57
58 /**
59 * An Amazon Fraud Detector list — a set of input values for a variable (an
60 * allow-list or deny-list, e.g. known-fraud IP addresses) referenced from
61 * detector rule expressions.
62 *
63 * ### Creating a List
64 * **Example:** Deny-list of IP Addresses
65 * ```typescript
66 * const blockedIps = yield* FraudDetector.List("BlockedIps", {
67 * variableType: "IP_ADDRESS",
68 * description: "known-fraud source addresses",
69 * elements: ["203.0.113.7", "198.51.100.9"],
70 * });
71 * ```
72 *
73 * ### Using a List at Runtime
74 * **Example:** Append to the List from a Lambda
75 * ```typescript
76 * // init
77 * const updateList = yield* FraudDetector.UpdateList(blockedIps);
78 * const getListElements = yield* FraudDetector.GetListElements(blockedIps);
79 *
80 * // runtime
81 * yield* updateList({ elements: ["192.0.2.44"], updateMode: "APPEND" });
82 * const { elements } = yield* getListElements({});
83 * // on the Function effect:
84 * // .pipe(Effect.provide(Layer.mergeAll(
85 * // FraudDetector.UpdateListHttp,
86 * // FraudDetector.GetListElementsHttp,
87 * // )))
88 * ```
89 *
90 * @resource
91 */
92 export const List = Resource<List>("AWS.FraudDetector.List");
93
94 /** Coerce a distilled sensitive element (`string | Redacted<string>`) to a plain string. */
95 const toElement = (e: string | Redacted.Redacted<string>): string =>
96 typeof e === "string" ? e : Redacted.value(e);
97
98 export const ListProvider = () =>
99 Provider.effect(
100 List,
101 Effect.gen(function* () {
102 const createName = Effect.fn(function* (id: string, props: ListProps) {
103 return props.name ?? (yield* createPhysicalName({ id, maxLength: 64, lowercase: true }));
104 });
105
106 /** Look a list's metadata up by name; typed not-found → undefined. */
107 const get = Effect.fn(function* (name: string) {
108 const response = yield* frauddetector
109 .getListsMetadata({ name })
110 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
111 return response?.lists?.find((list) => list.name === name);
112 });
113
114 /** Read the full (paginated) element set of a list. */
115 const getElements = Effect.fn(function* (name: string) {
116 const pages = yield* frauddetector.getListElements.pages({ name }).pipe(Stream.runCollect);
117 return Array.from(pages).flatMap((page) => (page.elements ?? []).map(toElement));
118 });
119
120 const toAttrs = (list: frauddetector.AllowDenyList) => ({
121 name: list.name,
122 arn: list.arn!,
123 });
124
125 return {
126 stables: ["name", "arn"],
127
128 diff: Effect.fn(function* ({ id, olds = {}, news }) {
129 if (!isResolved(news)) return undefined;
130 const oldName = yield* createName(id, olds);
131 const newName = yield* createName(id, news);
132 if (
133 oldName !== newName ||
134 // The variable type can only be set once — changing an
135 // already-set variable type requires a replacement.
136 (olds.variableType !== undefined && news.variableType !== olds.variableType)
137 ) {
138 return { action: "replace" } as const;
139 }
140 }),
141
142 read: Effect.fn(function* ({ id, olds, output }) {
143 const name = output?.name ?? (yield* createName(id, olds ?? {}));
144 const list = yield* get(name);
145 if (list === undefined) return undefined;
146 const attrs = toAttrs(list);
147 const tags = yield* readFraudDetectorTags(list.arn!);
148 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
149 }),
150
151 reconcile: Effect.fn(function* ({ id, news = {}, session }) {
152 const name = yield* createName(id, news);
153 const internalTags = yield* createInternalTags(id);
154 const desiredTags = { ...internalTags, ...news.tags };
155 const desiredElements = news.elements ?? [];
156
157 // Observe — the live list is authoritative.
158 let list = yield* get(name);
159
160 if (list === undefined) {
161 // Ensure — greenfield create carries the full desired state.
162 yield* frauddetector.createList({
163 name,
164 description: news.description,
165 variableType: news.variableType,
166 elements: desiredElements,
167 tags: Object.entries(desiredTags).map(([key, value]) => ({
168 key,
169 value,
170 })),
171 });
172 list = yield* get(name);
173 } else {
174 // Sync — diff each mutable aspect against OBSERVED state and send
175 // only the delta.
176 const observedElements = yield* getElements(name);
177 const desiredSet = new Set(desiredElements);
178 const observedSet = new Set(observedElements);
179 const elementsChanged =
180 desiredSet.size !== observedSet.size ||
181 Array.from(desiredSet).some((e) => !observedSet.has(e));
182 const descriptionChanged =
183 (news.description ?? undefined) !== (list.description ?? undefined);
184 // The variable type can only be introduced, never changed (a
185 // change is a replacement, handled by diff above).
186 const variableTypeIntroduced =
187 list.variableType === undefined && news.variableType !== undefined;
188
189 if (elementsChanged || descriptionChanged || variableTypeIntroduced) {
190 yield* frauddetector.updateList({
191 name,
192 ...(elementsChanged ? { elements: desiredElements, updateMode: "REPLACE" } : {}),
193 ...(descriptionChanged ? { description: news.description } : {}),
194 ...(variableTypeIntroduced ? { variableType: news.variableType } : {}),
195 });
196 list = yield* get(name);
197 }
198 }
199
200 // Sync tags — diff against OBSERVED cloud tags.
201 yield* syncFraudDetectorTags(list!.arn!, desiredTags);
202
203 yield* session.note(name);
204 return toAttrs(list!);
205 }),
206
207 delete: Effect.fn(function* ({ output }) {
208 yield* frauddetector.deleteList({ name: output.name }).pipe(
209 // Deleting an already-removed list is a no-op for us; Fraud
210 // Detector surfaces a missing list as a validation error.
211 Effect.catchTag("ValidationException", () => Effect.void),
212 );
213 }),
214
215 list: () =>
216 frauddetector.getListsMetadata.pages({}).pipe(
217 Stream.runCollect,
218 Effect.map((chunk) =>
219 Array.from(chunk).flatMap((page) => (page.lists ?? []).map(toAttrs)),
220 ),
221 ),
222 };
223 }),
224 );