@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 276 lines 10.1 KB
Raw
1 import * as securitylake from "@distilled.cloud/aws/securitylake";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Redacted from "effect/Redacted";
7 import * as Stream from "effect/Stream";
8 import type { Providers } from "../Providers.ts";
9 import { retryWhileConflict } from "./internal.ts";
10
11 /**
12 * HTTPS delivery settings for a subscriber notification.
13 */
14 export interface SubscriberHttpsNotificationConfiguration {
15 /** The HTTPS endpoint Security Lake POSTs/PUTs object notifications to. */
16 endpoint: string;
17 /**
18 * ARN of the EventBridge API-destination role Security Lake assumes to
19 * invoke the endpoint.
20 */
21 targetRoleArn: string;
22 /**
23 * Name of the API-key header sent with each notification.
24 */
25 authorizationApiKeyName?: string;
26 /**
27 * Value of the API-key header sent with each notification. Held as a
28 * `Redacted` secret; it is never persisted or logged in plaintext.
29 */
30 authorizationApiKeyValue?: Redacted.Redacted<string>;
31 /**
32 * The HTTP method used to deliver notifications.
33 * @default "POST"
34 */
35 httpMethod?: "POST" | "PUT";
36 }
37
38 export interface SubscriberNotificationProps {
39 /**
40 * ID of the `SecurityLake.Subscriber` the notification is configured for.
41 * Changing this replaces the notification.
42 */
43 subscriberId: string;
44
45 /**
46 * Deliver new-object notifications to an AWS-managed SQS queue (Security
47 * Lake creates the queue). Exactly one of `sqs` or
48 * `httpsNotificationConfiguration` must be set.
49 * @default false
50 */
51 sqs?: boolean;
52
53 /**
54 * Deliver new-object notifications to a custom HTTPS endpoint. Exactly one
55 * of `sqs` or `httpsNotificationConfiguration` must be set.
56 */
57 httpsNotificationConfiguration?: SubscriberHttpsNotificationConfiguration;
58 }
59
60 /** @resource */
61 export interface SubscriberNotification extends Resource<
62 "AWS.SecurityLake.SubscriberNotification",
63 SubscriberNotificationProps,
64 {
65 /** ID of the subscriber the notification belongs to. */
66 subscriberId: string;
67 /**
68 * The notification endpoint — the ARN of the AWS-managed SQS queue, or
69 * the configured HTTPS endpoint.
70 */
71 subscriberEndpoint: string | undefined;
72 },
73 never,
74 Providers
75 > {}
76
77 /**
78 * A Security Lake subscriber notification — notifies a data-access
79 * subscriber whenever new objects land in its Security Lake bucket, either
80 * via an AWS-managed SQS queue or a custom HTTPS endpoint.
81 *
82 * ### Notifying subscribers
83 * **Example:** SQS notifications
84 * ```typescript
85 * const notification = yield* SecurityLake.SubscriberNotification("Notify", {
86 * subscriberId: subscriber.subscriberId,
87 * sqs: true,
88 * });
89 * ```
90 *
91 * **Example:** HTTPS notifications with an API key
92 * ```typescript
93 * const notification = yield* SecurityLake.SubscriberNotification("Notify", {
94 * subscriberId: subscriber.subscriberId,
95 * httpsNotificationConfiguration: {
96 * endpoint: "https://ingest.example.com/securitylake",
97 * targetRoleArn: eventsRole.roleArn,
98 * authorizationApiKeyName: "x-api-key",
99 * authorizationApiKeyValue: Redacted.make("super-secret"),
100 * },
101 * });
102 * ```
103 */
104 const SubscriberNotificationResource = Resource<SubscriberNotification>(
105 "AWS.SecurityLake.SubscriberNotification",
106 );
107
108 export { SubscriberNotificationResource as SubscriberNotification };
109
110 // Build the wire NotificationConfiguration from props. Redacted secrets are
111 // passed through intact — distilled's SensitiveString accepts Redacted.
112 const toWireConfiguration = (
113 props: SubscriberNotificationProps,
114 ): securitylake.NotificationConfiguration =>
115 props.httpsNotificationConfiguration !== undefined
116 ? { httpsNotificationConfiguration: props.httpsNotificationConfiguration }
117 : { sqsNotificationConfiguration: {} };
118
119 // A comparable, secret-free serialization of the desired configuration used
120 // to skip no-op updates (the API does not expose the current configuration,
121 // only the resulting endpoint — `olds` is the hint here).
122 const configFingerprint = (props: {
123 sqs?: boolean;
124 httpsNotificationConfiguration?: SubscriberHttpsNotificationConfiguration;
125 }): string => {
126 const https = props.httpsNotificationConfiguration;
127 return https !== undefined
128 ? JSON.stringify({
129 endpoint: https.endpoint,
130 targetRoleArn: https.targetRoleArn,
131 authorizationApiKeyName: https.authorizationApiKeyName,
132 // `olds` may have round-tripped through persisted state, so the
133 // secret may no longer be a live Redacted — guard before unwrapping.
134 authorizationApiKeyValue:
135 https.authorizationApiKeyValue !== undefined
136 ? Redacted.isRedacted(https.authorizationApiKeyValue)
137 ? Redacted.value(https.authorizationApiKeyValue)
138 : String(https.authorizationApiKeyValue)
139 : undefined,
140 httpMethod: https.httpMethod ?? "POST",
141 })
142 : "sqs";
143 };
144
145 const getSubscriberEndpoint = (subscriberId: string) =>
146 securitylake
147 .getSubscriber({ subscriberId })
148 .pipe(Effect.map((response) => response.subscriber?.subscriberEndpoint));
149
150 export const SubscriberNotificationProvider = () =>
151 Provider.effect(
152 SubscriberNotificationResource,
153 Effect.gen(function* () {
154 return {
155 read: Effect.fn(function* ({ olds, output }) {
156 const subscriberId = output?.subscriberId ?? olds?.subscriberId;
157 if (subscriberId === undefined) return undefined;
158 // A missing subscriber (or an account that never onboarded
159 // Security Lake) means "no notification", not a failure.
160 const endpoint = yield* getSubscriberEndpoint(subscriberId).pipe(
161 Effect.catchTag(
162 ["ResourceNotFoundException", "UnauthorizedException"],
163 () => Effect.undefined,
164 ),
165 );
166 // Notifications carry no tags, so ownership can't be
167 // distinguished — read reports observed state directly.
168 return endpoint === undefined
169 ? undefined
170 : { subscriberId, subscriberEndpoint: endpoint };
171 }),
172
173 // A notification exists only for subscribers that report a
174 // notification endpoint.
175 list: () =>
176 securitylake.listSubscribers.items({}).pipe(
177 Stream.filter((subscriber) => subscriber.subscriberEndpoint !== undefined),
178 Stream.runCollect,
179 Effect.map((subscribers) =>
180 [...subscribers].map((subscriber) => ({
181 subscriberId: subscriber.subscriberId,
182 subscriberEndpoint: subscriber.subscriberEndpoint,
183 })),
184 ),
185 // An account that never onboarded Security Lake has no
186 // subscribers to enumerate.
187 Effect.catchTag(
188 ["AccessDeniedException", "ResourceNotFoundException", "UnauthorizedException"],
189 () => Effect.succeed([]),
190 ),
191 ),
192
193 // The notification is per-subscriber; changing the subscriber
194 // replaces it.
195 diff: Effect.fn(function* ({ news, olds }) {
196 if (!isResolved(news)) return undefined;
197 if (news.subscriberId !== olds.subscriberId) {
198 return { action: "replace" } as const;
199 }
200 }),
201
202 reconcile: Effect.fn(function* ({ news, olds, output, session }) {
203 const configuration = toWireConfiguration(news);
204
205 // 1. OBSERVE — the subscriber's current notification endpoint.
206 const observedEndpoint = yield* getSubscriberEndpoint(news.subscriberId);
207
208 let endpoint = observedEndpoint;
209 if (observedEndpoint === undefined) {
210 // 2. ENSURE — create when missing. A ConflictException means a
211 // concurrent create won the race; converge via update.
212 endpoint = yield* securitylake
213 .createSubscriberNotification({
214 subscriberId: news.subscriberId,
215 configuration,
216 })
217 .pipe(
218 Effect.map((response) => response.subscriberEndpoint),
219 Effect.catchTag("ConflictException", () =>
220 securitylake
221 .updateSubscriberNotification({
222 subscriberId: news.subscriberId,
223 configuration,
224 })
225 .pipe(
226 retryWhileConflict,
227 Effect.map((response) => response.subscriberEndpoint),
228 ),
229 ),
230 );
231 } else if (
232 output === undefined ||
233 olds === undefined ||
234 configFingerprint(olds) !== configFingerprint(news)
235 ) {
236 // 3. SYNC — the API reports only the endpoint, not the
237 // configuration, so `olds` is the no-op hint; adoption always
238 // converges via an idempotent update.
239 endpoint = yield* securitylake
240 .updateSubscriberNotification({
241 subscriberId: news.subscriberId,
242 configuration,
243 })
244 .pipe(
245 retryWhileConflict,
246 Effect.map((response) => response.subscriberEndpoint ?? endpoint),
247 );
248 }
249
250 // 4. RETURN fresh attributes.
251 const final = endpoint ?? (yield* getSubscriberEndpoint(news.subscriberId));
252 yield* session.note(final ?? news.subscriberId);
253 return {
254 subscriberId: news.subscriberId,
255 subscriberEndpoint: final,
256 };
257 }),
258
259 delete: Effect.fn(function* ({ output }) {
260 yield* securitylake
261 .deleteSubscriberNotification({
262 subscriberId: output.subscriberId,
263 })
264 .pipe(
265 retryWhileConflict,
266 // Gone already, the subscriber was deleted first, or the data
267 // lake itself was offboarded.
268 Effect.catchTag(
269 ["AccessDeniedException", "ResourceNotFoundException", "UnauthorizedException"],
270 () => Effect.void,
271 ),
272 );
273 }),
274 };
275 }),
276 );