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

main
ts 275 lines 10.9 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 { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, createTagsList, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { AWSEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12
13 export interface CustomVerificationEmailTemplateProps {
14 /**
15 * Name of the template. May contain letters, numbers, dashes and
16 * underscores, up to 64 characters. If omitted, a deterministic physical
17 * name is generated from the app, stage, and logical ID. Changing the name
18 * replaces the template.
19 */
20 templateName?: string;
21 /**
22 * The verified email address the verification email is sent from. The
23 * identity must already be verified for sending.
24 */
25 fromEmailAddress: string;
26 /**
27 * The subject line of the verification email.
28 */
29 templateSubject: string;
30 /**
31 * The HTML body of the verification email. Must contain a link to the
32 * verification URL SES generates.
33 */
34 templateContent: string;
35 /**
36 * The URL the recipient is redirected to after successfully verifying.
37 */
38 successRedirectionURL: string;
39 /**
40 * The URL the recipient is redirected to if verification fails.
41 */
42 failureRedirectionURL: string;
43 /**
44 * Tags to apply to the template. Merged with internal Alchemy tags.
45 */
46 tags?: Record<string, string>;
47 }
48
49 export interface CustomVerificationEmailTemplate extends Resource<
50 "AWS.SES.CustomVerificationEmailTemplate",
51 CustomVerificationEmailTemplateProps,
52 {
53 /** Name of the template. */
54 templateName: string;
55 },
56 never,
57 Providers
58 > {}
59
60 /**
61 * An Amazon SES v2 custom verification email template — the branded email SES
62 * sends when you verify a new email-address identity via
63 * `SendCustomVerificationEmail`.
64 *
65 * Creating, reading, updating, and deleting the template works on any account.
66 * Actually *sending* a custom verification email requires the account to be
67 * out of the SES sandbox (production access).
68 * ### Creating Templates
69 * **Example:** Branded Verification Email
70 * ```typescript
71 * import * as SES from "@alchemy.run/aws/SES";
72 *
73 * const template = yield* SES.CustomVerificationEmailTemplate("Verify", {
74 * fromEmailAddress: "verify@example.com",
75 * templateSubject: "Please confirm your email",
76 * templateContent:
77 * "<html><body>Click the link to verify your address.</body></html>",
78 * successRedirectionURL: "https://example.com/verified",
79 * failureRedirectionURL: "https://example.com/verify-failed",
80 * });
81 * ```
82 *
83 * **Example:** Explicit Template Name
84 * ```typescript
85 * // Without templateName a deterministic name is derived from app/stage/id.
86 * const template = yield* SES.CustomVerificationEmailTemplate("Verify", {
87 * templateName: "onboarding-verification",
88 * fromEmailAddress: "verify@example.com",
89 * templateSubject: "Please confirm your email",
90 * templateContent:
91 * "<html><body>Click the link to verify your address.</body></html>",
92 * successRedirectionURL: "https://example.com/verified",
93 * failureRedirectionURL: "https://example.com/verify-failed",
94 * });
95 * ```
96 *
97 * ### Sending the Verification Email
98 * **Example:** Verify a New Address from a Lambda Function
99 * ```typescript
100 * // init — account-level binding, no resource argument
101 * const sendVerification = yield* SES.SendCustomVerificationEmail();
102 *
103 * // runtime — SES emails the branded template to the address, and the
104 * // address becomes a verified identity once the recipient clicks through.
105 * const { MessageId } = yield* sendVerification({
106 * EmailAddress: "new-user@example.com",
107 * TemplateName: yield* template.templateName,
108 * });
109 * ```
110 *
111 * @resource
112 */
113 export const CustomVerificationEmailTemplate = Resource<CustomVerificationEmailTemplate>(
114 "AWS.SES.CustomVerificationEmailTemplate",
115 );
116
117 const toTagRecord = (
118 tags: ReadonlyArray<{ Key: string; Value: string }> | undefined,
119 ): Record<string, string> => Object.fromEntries((tags ?? []).map((tag) => [tag.Key, tag.Value]));
120
121 // getCustomVerificationEmailTemplate returns no ARN, so the ARN
122 // listTagsForResource needs is derived — verified live against SES.
123 const templateArnOf = (region: string, accountId: string, name: string) =>
124 `arn:aws:ses:${region}:${accountId}:custom-verification-email-template/${name}`;
125
126 export const CustomVerificationEmailTemplateProvider = () =>
127 Provider.effect(
128 CustomVerificationEmailTemplate,
129 Effect.gen(function* () {
130 const createName = Effect.fn(function* (
131 id: string,
132 props: Pick<CustomVerificationEmailTemplateProps, "templateName">,
133 ) {
134 return props.templateName ?? (yield* createPhysicalName({ id, maxLength: 64 }));
135 });
136
137 const getTemplate = Effect.fn(function* (name: string) {
138 return yield* sesv2
139 .getCustomVerificationEmailTemplate({ TemplateName: name })
140 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
141 });
142
143 // The get returns no tags, so ownership costs a second API call. Only
144 // `read` pays it — `list` deletes by name.
145 const getTemplateTags = Effect.fn(function* (name: string) {
146 const { accountId, region } = yield* AWSEnvironment.current;
147 return yield* sesv2
148 .listTagsForResource({
149 ResourceArn: templateArnOf(region, accountId, name),
150 })
151 .pipe(
152 Effect.map((response) => toTagRecord(response.Tags)),
153 Effect.catchTag("NotFoundException", () =>
154 Effect.succeed({} as Record<string, string>),
155 ),
156 );
157 });
158
159 return CustomVerificationEmailTemplate.Provider.of({
160 stables: ["templateName"],
161
162 // Account/region-scoped: enumerate every template so leaked test
163 // resources are cleaned by nuke. Custom verification email templates
164 // carry no ownership signal, so existence is treated as ownership.
165 list: Effect.fn(function* () {
166 const pages = yield* sesv2.listCustomVerificationEmailTemplates
167 .pages({})
168 .pipe(Stream.runCollect);
169 return Array.from(pages)
170 .flatMap((page) => page.CustomVerificationEmailTemplates ?? [])
171 .flatMap((meta) => (meta.TemplateName ? [{ templateName: meta.TemplateName }] : []));
172 }),
173
174 read: Effect.fn(function* ({ id, olds, output }) {
175 const name = output?.templateName ?? (yield* createName(id, olds ?? {}));
176 const found = yield* getTemplate(name);
177 if (!found) return undefined;
178 // Templates are taggable and reconcile brands the ones it creates,
179 // so existence at our deterministic name is not proof of ownership.
180 const tags = yield* getTemplateTags(name);
181 return (yield* hasAlchemyTags(id, tags))
182 ? { templateName: name }
183 : Unowned({ templateName: name });
184 }),
185
186 diff: Effect.fn(function* ({ id, news, olds }) {
187 if (!isResolved(news)) return undefined;
188 const oldName = yield* createName(id, olds ?? {});
189 const newName = yield* createName(id, news ?? {});
190 if (oldName !== newName) {
191 return { action: "replace" } as const;
192 }
193 }),
194
195 reconcile: Effect.fn(function* ({ id, news, output }) {
196 const name = output?.templateName ?? (yield* createName(id, news));
197 const internalTags = yield* createInternalTags(id);
198 const desiredTags = { ...news.tags, ...internalTags };
199
200 // 1. OBSERVE — cloud state is authoritative.
201 const observed = yield* getTemplate(name);
202
203 if (observed === undefined) {
204 // 2. ENSURE — create; AlreadyExists is a race → converge via update.
205 yield* sesv2
206 .createCustomVerificationEmailTemplate({
207 TemplateName: name,
208 FromEmailAddress: news.fromEmailAddress,
209 TemplateSubject: news.templateSubject,
210 TemplateContent: news.templateContent,
211 SuccessRedirectionURL: news.successRedirectionURL,
212 FailureRedirectionURL: news.failureRedirectionURL,
213 Tags: createTagsList(desiredTags),
214 })
215 .pipe(
216 Effect.catchTag("AlreadyExistsException", () =>
217 sesv2.updateCustomVerificationEmailTemplate({
218 TemplateName: name,
219 FromEmailAddress: news.fromEmailAddress,
220 TemplateSubject: news.templateSubject,
221 TemplateContent: news.templateContent,
222 SuccessRedirectionURL: news.successRedirectionURL,
223 FailureRedirectionURL: news.failureRedirectionURL,
224 }),
225 ),
226 );
227 } else if (
228 observed.FromEmailAddress !== news.fromEmailAddress ||
229 observed.TemplateSubject !== news.templateSubject ||
230 observed.TemplateContent !== news.templateContent ||
231 observed.SuccessRedirectionURL !== news.successRedirectionURL ||
232 observed.FailureRedirectionURL !== news.failureRedirectionURL
233 ) {
234 // 3. SYNC — a single full-replace update converges the template.
235 yield* sesv2.updateCustomVerificationEmailTemplate({
236 TemplateName: name,
237 FromEmailAddress: news.fromEmailAddress,
238 TemplateSubject: news.templateSubject,
239 TemplateContent: news.templateContent,
240 SuccessRedirectionURL: news.successRedirectionURL,
241 FailureRedirectionURL: news.failureRedirectionURL,
242 });
243 }
244
245 // 4. SYNC TAGS — diff against OBSERVED cloud tags so an adopted
246 // template gets branded and stops reading as Unowned.
247 const observedTags = yield* getTemplateTags(name);
248 const { upsert, removed } = diffTags(observedTags, desiredTags);
249 if (upsert.length > 0 || removed.length > 0) {
250 const { accountId, region } = yield* AWSEnvironment.current;
251 const arn = templateArnOf(region, accountId, name);
252 if (upsert.length > 0) {
253 yield* sesv2.tagResource({ ResourceArn: arn, Tags: upsert });
254 }
255 if (removed.length > 0) {
256 yield* sesv2.untagResource({
257 ResourceArn: arn,
258 TagKeys: removed,
259 });
260 }
261 }
262
263 return { templateName: name };
264 }),
265
266 delete: Effect.fn(function* ({ output }) {
267 yield* sesv2
268 .deleteCustomVerificationEmailTemplate({
269 TemplateName: output.templateName,
270 })
271 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
272 }),
273 });
274 }),
275 );