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

main
ts 443 lines 16.6 KB
Raw
1 import * as sesv2 from "@distilled.cloud/aws/sesv2";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, createTagsList, diffTags, hasAlchemyTags } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import { AWSEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 /**
13 * The length of the RSA key pair SES generates for Easy DKIM signing.
14 */
15 export type DkimSigningKeyLength = "RSA_1024_BIT" | "RSA_2048_BIT";
16
17 export interface EmailIdentityProps {
18 /**
19 * The email address or domain to verify with SES, e.g. `hello@example.com`
20 * or `example.com`. Changing this replaces the identity.
21 *
22 * - **Email address** — SES sends a verification email to the address; the
23 * identity stays `PENDING` until the link is clicked.
24 * - **Domain** — SES generates Easy DKIM tokens (see the `dkimTokens`
25 * attribute) that must be published as CNAME records; the identity stays
26 * `PENDING` until the DNS records propagate.
27 */
28 emailIdentity: string;
29 /**
30 * The configuration set to apply by default to messages sent from this
31 * identity. The configuration set must exist in the same region.
32 */
33 configurationSetName?: string;
34 /**
35 * The length of the private key SES uses for Easy DKIM signing. Only
36 * applies to domain identities.
37 * @default "RSA_2048_BIT"
38 */
39 dkimSigningKeyLength?: DkimSigningKeyLength;
40 /**
41 * Whether Easy DKIM signing is enabled for the identity. Leave undefined to
42 * keep SES's current setting.
43 */
44 dkimSigningEnabled?: boolean;
45 /**
46 * Whether SES forwards bounce and complaint feedback to the identity's email
47 * address. Leave undefined to keep SES's current setting.
48 * @default true
49 */
50 feedbackForwardingEnabled?: boolean;
51 /**
52 * A custom MAIL FROM domain (a verified subdomain of the identity) SES uses
53 * in the message envelope. Publish the required MX and SPF records for the
54 * subdomain to complete setup. Leave undefined to keep SES's current
55 * setting — there is no removal path once one is configured.
56 */
57 mailFromDomain?: string;
58 /**
59 * What SES does when the custom MAIL FROM domain's MX record can't be read:
60 * fall back to the SES default (`USE_DEFAULT_VALUE`) or reject the message
61 * (`REJECT_MESSAGE`).
62 * @default "USE_DEFAULT_VALUE"
63 */
64 mailFromBehaviorOnMxFailure?: sesv2.BehaviorOnMxFailure;
65 /**
66 * Tags to apply to the identity. Merged with internal Alchemy tags.
67 */
68 tags?: Record<string, string>;
69 }
70
71 export interface EmailIdentity extends Resource<
72 "AWS.SES.EmailIdentity",
73 EmailIdentityProps,
74 {
75 emailIdentity: string;
76 identityArn: string;
77 identityType: sesv2.IdentityType;
78 verifiedForSendingStatus: boolean;
79 verificationStatus: sesv2.VerificationStatus | undefined;
80 /**
81 * The Easy DKIM CNAME tokens for a domain identity. Publish each token as
82 * `{token}._domainkey.{domain} CNAME {token}.dkim.amazonses.com` to
83 * complete verification. Empty for email-address identities.
84 */
85 dkimTokens: string[];
86 dkimStatus: sesv2.DkimStatus | undefined;
87 /**
88 * Default configuration set, the declared DKIM, feedback-forwarding and
89 * MAIL FROM settings, and the tags, as observed. Lets `alchemy drift`
90 * detect out-of-band changes.
91 */
92 configuration?: {
93 configurationSetName?: string;
94 dkimSigningEnabled?: boolean;
95 dkimSigningKeyLength?: string;
96 feedbackForwardingEnabled?: boolean;
97 mailFromDomain?: string;
98 mailFromBehaviorOnMxFailure?: string;
99 tags: Record<string, string>;
100 };
101 },
102 never,
103 Providers
104 > {}
105
106 /**
107 * An Amazon SES v2 email identity — a verified email address or domain that
108 * you send email from.
109 *
110 * Creating the identity starts verification: email-address identities receive
111 * a verification email, and domain identities get Easy DKIM tokens (exposed
112 * as the `dkimTokens` attribute) to publish as CNAME records. The identity
113 * is usable for sending once `verificationStatus` is `SUCCESS`.
114 * ### Creating Identities
115 * **Example:** Domain Identity
116 * ```typescript
117 * import * as SES from "@alchemy.run/aws/SES";
118 *
119 * const identity = yield* SES.EmailIdentity("Sender", {
120 * emailIdentity: "mail.example.com",
121 * });
122 * // publish identity.dkimTokens as CNAME records to verify
123 * ```
124 *
125 * **Example:** Email Address Identity
126 * ```typescript
127 * const identity = yield* SES.EmailIdentity("Sender", {
128 * emailIdentity: "hello@example.com",
129 * });
130 * // SES emails hello@example.com a verification link
131 * ```
132 *
133 * ### Configuration Set Association
134 * **Example:** Apply a Configuration Set by Default
135 * ```typescript
136 * const configSet = yield* SES.ConfigurationSet("Tracking", {});
137 * const identity = yield* SES.EmailIdentity("Sender", {
138 * emailIdentity: "mail.example.com",
139 * configurationSetName: configSet.configurationSetName,
140 * });
141 * ```
142 *
143 * ### DKIM and Feedback
144 * **Example:** Turn Easy DKIM Signing Off
145 * ```typescript
146 * // Omit the prop entirely to leave SES's current setting alone.
147 * const identity = yield* SES.EmailIdentity("Sender", {
148 * emailIdentity: "mail.example.com",
149 * dkimSigningEnabled: false,
150 * });
151 * ```
152 *
153 * **Example:** Stop Forwarding Bounces and Complaints by Email
154 * ```typescript
155 * // Turn this off once a configuration set event destination is handling
156 * // bounces and complaints, so they stop arriving as mail.
157 * const identity = yield* SES.EmailIdentity("Sender", {
158 * emailIdentity: "mail.example.com",
159 * feedbackForwardingEnabled: false,
160 * });
161 * ```
162 *
163 * ### Custom MAIL FROM Domain
164 * **Example:** Send with Your Own Envelope Domain
165 * ```typescript
166 * // mailFromDomain must be a subdomain of the identity, and needs MX and
167 * // SPF records published before SES will use it.
168 * const identity = yield* SES.EmailIdentity("Sender", {
169 * emailIdentity: "mail.example.com",
170 * mailFromDomain: "bounce.mail.example.com",
171 * // Reject rather than silently falling back to the SES default when the
172 * // MX record cannot be read.
173 * mailFromBehaviorOnMxFailure: "REJECT_MESSAGE",
174 * });
175 * ```
176 *
177 * ### Sending Email at Runtime
178 * **Example:** Send Through the Identity from a Lambda Function
179 * ```typescript
180 * // init
181 * const sendEmail = yield* SES.SendEmail(identity);
182 *
183 * // runtime
184 * const result = yield* sendEmail({
185 * FromEmailAddress: "hello@mail.example.com",
186 * Destination: { ToAddresses: ["customer@example.com"] },
187 * Content: {
188 * Simple: {
189 * Subject: { Data: "Welcome!" },
190 * Body: { Text: { Data: "Hello from SES." } },
191 * },
192 * },
193 * });
194 * ```
195 *
196 * @resource
197 */
198 export const EmailIdentity = Resource<EmailIdentity>("AWS.SES.EmailIdentity");
199
200 const toTagRecord = (
201 tags: ReadonlyArray<{ Key: string; Value: string }> | undefined,
202 ): Record<string, string> => Object.fromEntries((tags ?? []).map((tag) => [tag.Key, tag.Value]));
203
204 const identityArnOf = (region: string, accountId: string, name: string) =>
205 `arn:aws:ses:${region}:${accountId}:identity/${name}`;
206
207 const toAttributes = (
208 name: string,
209 identityArn: string,
210 identity: sesv2.GetEmailIdentityResponse,
211 ) => ({
212 emailIdentity: name,
213 identityArn,
214 identityType: identity.IdentityType ?? "DOMAIN",
215 verifiedForSendingStatus: identity.VerifiedForSendingStatus ?? false,
216 verificationStatus: identity.VerificationStatus,
217 dkimTokens: [...(identity.DkimAttributes?.Tokens ?? [])],
218 dkimStatus: identity.DkimAttributes?.Status,
219 });
220
221 /**
222 * The settings reconcile converges, as observed. Settings reconcile only
223 * applies when declared are only observed when declared. `read` and
224 * `reconcile` share it so a converged identity reads unchanged.
225 */
226 const observeIdentityConfiguration = (
227 identity: sesv2.GetEmailIdentityResponse,
228 props: EmailIdentityProps | undefined,
229 tags: Record<string, string>,
230 ) => ({
231 configurationSetName: identity.ConfigurationSetName,
232 dkimSigningEnabled:
233 props?.dkimSigningEnabled === undefined
234 ? undefined
235 : (identity.DkimAttributes?.SigningEnabled ?? false),
236 dkimSigningKeyLength:
237 props?.dkimSigningKeyLength === undefined
238 ? undefined
239 : identity.DkimAttributes?.NextSigningKeyLength,
240 feedbackForwardingEnabled:
241 props?.feedbackForwardingEnabled === undefined
242 ? undefined
243 : (identity.FeedbackForwardingStatus ?? true),
244 mailFromDomain:
245 props?.mailFromDomain === undefined ? undefined : identity.MailFromAttributes?.MailFromDomain,
246 mailFromBehaviorOnMxFailure:
247 props?.mailFromDomain === undefined || props.mailFromBehaviorOnMxFailure === undefined
248 ? undefined
249 : identity.MailFromAttributes?.BehaviorOnMxFailure,
250 tags,
251 });
252
253 export const EmailIdentityProvider = () =>
254 Provider.effect(
255 EmailIdentity,
256 Effect.gen(function* () {
257 const getIdentity = Effect.fn(function* (name: string) {
258 return yield* sesv2
259 .getEmailIdentity({ EmailIdentity: name })
260 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
261 });
262
263 return EmailIdentity.Provider.of({
264 stables: ["emailIdentity", "identityArn"],
265
266 list: () =>
267 Effect.gen(function* () {
268 const { accountId, region } = yield* AWSEnvironment.current;
269 const pages = yield* sesv2.listEmailIdentities.pages({}).pipe(Stream.runCollect);
270 const infos = Array.from(pages).flatMap((page) => page.EmailIdentities ?? []);
271 const attrs = yield* Effect.forEach(
272 infos.filter(
273 (info): info is typeof info & { IdentityName: string } => info.IdentityName != null,
274 ),
275 (info) =>
276 Effect.gen(function* () {
277 const identity = yield* getIdentity(info.IdentityName);
278 return identity === undefined
279 ? undefined
280 : toAttributes(
281 info.IdentityName,
282 identityArnOf(region, accountId, info.IdentityName),
283 identity,
284 );
285 }),
286 { concurrency: 2 },
287 );
288 return attrs.filter((a) => a !== undefined);
289 }),
290
291 read: Effect.fn(function* ({ id, olds, output }) {
292 const { accountId, region } = yield* AWSEnvironment.current;
293 const name = output?.emailIdentity ?? olds?.emailIdentity;
294 if (name === undefined) return undefined;
295 const found = yield* getIdentity(name);
296 if (!found) return undefined;
297 const tags = toTagRecord(found.Tags);
298 const attrs = {
299 ...toAttributes(name, identityArnOf(region, accountId, name), found),
300 configuration: observeIdentityConfiguration(found, olds, tags),
301 };
302 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
303 }),
304
305 diff: Effect.fn(function* ({ news, olds }) {
306 if (!isResolved(news)) return undefined;
307 if (
308 olds?.emailIdentity !== undefined &&
309 news?.emailIdentity !== undefined &&
310 olds.emailIdentity !== news.emailIdentity
311 ) {
312 return { action: "replace" } as const;
313 }
314 }),
315
316 reconcile: Effect.fn(function* ({ id, news, output, session }) {
317 const { accountId, region } = yield* AWSEnvironment.current;
318 const name = output?.emailIdentity ?? news.emailIdentity;
319 const identityArn = identityArnOf(region, accountId, name);
320 const internalTags = yield* createInternalTags(id);
321 const desiredTags = { ...news.tags, ...internalTags };
322
323 // 1. OBSERVE — cloud state is authoritative; `output` is only a
324 // cache of the identity name.
325 let observed = yield* getIdentity(name);
326
327 // 2. ENSURE — create if missing; AlreadyExists is a race, not a
328 // failure. Creation kicks off verification (email or DKIM DNS).
329 if (observed === undefined) {
330 yield* sesv2
331 .createEmailIdentity({
332 EmailIdentity: name,
333 ConfigurationSetName: news.configurationSetName,
334 DkimSigningAttributes:
335 news.dkimSigningKeyLength !== undefined
336 ? { NextSigningKeyLength: news.dkimSigningKeyLength }
337 : undefined,
338 Tags: createTagsList(desiredTags),
339 })
340 .pipe(Effect.catchTag("AlreadyExistsException", () => Effect.succeed({})));
341 observed = yield* sesv2.getEmailIdentity({ EmailIdentity: name });
342 }
343
344 // 3. SYNC configuration-set association — compare observed against
345 // desired; passing undefined removes the association.
346 if (observed.ConfigurationSetName !== news.configurationSetName) {
347 yield* sesv2.putEmailIdentityConfigurationSetAttributes({
348 EmailIdentity: name,
349 ConfigurationSetName: news.configurationSetName,
350 });
351 }
352
353 // 3b. SYNC Easy DKIM signing key length (domain identities). Only
354 // applied when explicitly requested and observably different —
355 // rotating the key regenerates the DKIM tokens.
356 if (
357 news.dkimSigningKeyLength !== undefined &&
358 observed.DkimAttributes?.NextSigningKeyLength !== undefined &&
359 observed.DkimAttributes.NextSigningKeyLength !== news.dkimSigningKeyLength
360 ) {
361 yield* sesv2.putEmailIdentityDkimSigningAttributes({
362 EmailIdentity: name,
363 SigningAttributesOrigin: "AWS_SES",
364 SigningAttributes: {
365 NextSigningKeyLength: news.dkimSigningKeyLength,
366 },
367 });
368 }
369
370 // 3c. SYNC Easy DKIM signing enablement — only applied when
371 // explicitly requested and observably different.
372 if (
373 news.dkimSigningEnabled !== undefined &&
374 (observed.DkimAttributes?.SigningEnabled ?? false) !== news.dkimSigningEnabled
375 ) {
376 yield* sesv2.putEmailIdentityDkimAttributes({
377 EmailIdentity: name,
378 SigningEnabled: news.dkimSigningEnabled,
379 });
380 }
381
382 // 3d. SYNC feedback forwarding — only applied when explicitly
383 // requested and observably different (SES defaults it to on).
384 if (
385 news.feedbackForwardingEnabled !== undefined &&
386 (observed.FeedbackForwardingStatus ?? true) !== news.feedbackForwardingEnabled
387 ) {
388 yield* sesv2.putEmailIdentityFeedbackAttributes({
389 EmailIdentity: name,
390 EmailForwardingEnabled: news.feedbackForwardingEnabled,
391 });
392 }
393
394 // 3e. SYNC custom MAIL FROM domain — only applied when explicitly
395 // requested and observably different.
396 if (
397 news.mailFromDomain !== undefined &&
398 (observed.MailFromAttributes?.MailFromDomain !== news.mailFromDomain ||
399 (news.mailFromBehaviorOnMxFailure !== undefined &&
400 observed.MailFromAttributes?.BehaviorOnMxFailure !==
401 news.mailFromBehaviorOnMxFailure))
402 ) {
403 yield* sesv2.putEmailIdentityMailFromAttributes({
404 EmailIdentity: name,
405 MailFromDomain: news.mailFromDomain,
406 BehaviorOnMxFailure: news.mailFromBehaviorOnMxFailure,
407 });
408 }
409
410 // 3f. SYNC TAGS — diff against OBSERVED cloud tags so adoption
411 // converges.
412 const observedTags = toTagRecord(observed.Tags);
413 const { upsert, removed } = diffTags(observedTags, desiredTags);
414 if (upsert.length > 0) {
415 yield* sesv2.tagResource({
416 ResourceArn: identityArn,
417 Tags: upsert,
418 });
419 }
420 if (removed.length > 0) {
421 yield* sesv2.untagResource({
422 ResourceArn: identityArn,
423 TagKeys: removed,
424 });
425 }
426
427 // 4. RETURN — re-read so DKIM tokens/status reflect any sync above.
428 const final = yield* sesv2.getEmailIdentity({ EmailIdentity: name });
429 yield* session.note(identityArn);
430 return {
431 ...toAttributes(name, identityArn, final),
432 configuration: observeIdentityConfiguration(final, news, desiredTags),
433 };
434 }),
435
436 delete: Effect.fn(function* ({ output }) {
437 yield* sesv2
438 .deleteEmailIdentity({ EmailIdentity: output.emailIdentity })
439 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
440 }),
441 });
442 }),
443 );