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

main
ts 264 lines 10.4 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import {
3 ActiveReceiptRuleSet,
4 EmailIdentity,
5 ReceiptRule,
6 ReceiptRuleSet,
7 } from "@alchemy.run/aws/SES";
8 import * as Cloudflare from "@alchemy.run/cloudflare";
9 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
10 import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup";
11 import { expect } from "@alchemy.run/test";
12 import * as Test from "@alchemy.run/test/Alchemy";
13 import * as s3 from "@distilled.cloud/aws/s3";
14 import * as ses from "@distilled.cloud/aws/ses";
15 import * as sesv2 from "@distilled.cloud/aws/sesv2";
16 import * as sts from "@distilled.cloud/aws/sts";
17 import { adopt } from "alchemy/AdoptPolicy";
18 import * as Output from "alchemy/Output";
19 import * as Effect from "effect/Effect";
20 import * as Layer from "effect/Layer";
21 import * as Schedule from "effect/Schedule";
22 import * as Stream from "effect/Stream";
23
24 const { test } = Test.make({
25 providers: Layer.mergeAll(AWS.providers(), Cloudflare.providers()),
26 });
27
28 // End-to-end email receiving: verified domain + MX -> SES inbound -> receipt
29 // rule -> S3. The loop is fully automatable (the SES sandbox allows sends both
30 // FROM and TO a verified domain identity, and receiving itself never requires
31 // verification), but Easy-DKIM detection takes minutes and the suite needs the
32 // standing Cloudflare test zone + Cloudflare credentials — so the test is
33 // env-gated per the speed doctrine. Run with:
34 //
35 // AWS_TEST_SES_RECEIVING=1 bun run test test/AWS/SES/Receiving.smoke.test.ts --profile testing
36 const GATED = !process.env.AWS_TEST_SES_RECEIVING;
37
38 const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
39 // SES receiving is regional; the testing profile deploys to us-west-2 (one of
40 // the receiving-supported regions).
41 const region = process.env.AWS_TEST_SES_RECEIVING_REGION ?? "us-west-2";
42
43 // Deterministic names — same on every run, disjoint from other suites.
44 const domain = `ses-rcv-e2e.${zoneName}`;
45 const recipient = `inbox@${domain}`;
46 const SUBJECT_MARKER = "alchemy-ses-receiving-e2e";
47
48 const resolveZoneId = Effect.gen(function* () {
49 const { accountId } = yield* yield* CloudflareEnvironment;
50 const zone = yield* findZoneByName({ accountId, name: zoneName });
51 if (!zone) {
52 return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`));
53 }
54 return zone.id;
55 });
56
57 const activeRuleSetName = ses
58 .describeActiveReceiptRuleSet({})
59 .pipe(Effect.map((response) => response.Metadata?.Name));
60
61 // Mutates the account-singleton active receipt rule set: holds the
62 // "aws:ses-account" label, and the
63 // previously active set (if any) is captured and restored.
64 test.provider.skipIf(GATED)(
65 "end-to-end receive: MX -> SES inbound -> receipt rule -> S3 object",
66 (stack) =>
67 Effect.gen(function* () {
68 const zoneId = yield* resolveZoneId;
69 const { Account } = yield* sts.getCallerIdentity({});
70 const bucketName = `alchemy-ses-rcv-e2e-${Account}`;
71 const captured = yield* activeRuleSetName;
72
73 yield* Effect.gen(function* () {
74 yield* stack.destroy();
75
76 yield* stack.deploy(
77 Effect.gen(function* () {
78 // Domain identity; Easy DKIM CNAMEs published to the test zone
79 // verify it for the sandbox send below. Receiving itself does not
80 // require verification.
81 const identity = yield* EmailIdentity("RcvIdentity", {
82 emailIdentity: domain,
83 });
84 const dkim = (index: number) =>
85 Output.all(identity.dkimTokens).pipe(Output.map(([tokens]) => tokens[index]!));
86 // DNS records carry no ownership tags, so adopt-by-name is the
87 // standing-zone convention (see DnsRecord.test.ts) — it also
88 // converges over records orphaned by an interrupted run.
89 for (const index of [0, 1, 2]) {
90 yield* Cloudflare.DNS.Record(`Dkim${index}`, {
91 zoneId,
92 name: dkim(index).pipe(Output.map((token) => `${token}._domainkey.${domain}`)),
93 type: "CNAME",
94 content: dkim(index).pipe(Output.map((token) => `${token}.dkim.amazonses.com`)),
95 ttl: 60,
96 }).pipe(adopt(true));
97 }
98
99 // Route the subdomain's mail to SES inbound.
100 yield* Cloudflare.DNS.Record("Mx", {
101 zoneId,
102 name: domain,
103 type: "MX",
104 content: `inbound-smtp.${region}.amazonaws.com`,
105 priority: 10,
106 ttl: 60,
107 }).pipe(adopt(true));
108
109 // Inbound bucket. SES receiving writes via the bucket policy (no
110 // IAM role involved), so the policy must grant ses.amazonaws.com
111 // before the receipt rule below validates it.
112 const bucket = yield* AWS.S3.Bucket("RcvBucket", {
113 bucketName,
114 forceDestroy: true,
115 policy: [
116 {
117 Sid: "AllowSESPuts",
118 Effect: "Allow",
119 Principal: { Service: "ses.amazonaws.com" },
120 Action: ["s3:PutObject"],
121 Resource: `arn:aws:s3:::${bucketName}/*`,
122 Condition: {
123 StringEquals: { "aws:SourceAccount": Account! },
124 },
125 },
126 ],
127 });
128
129 const ruleSet = yield* ReceiptRuleSet("RcvSet", {});
130 yield* ReceiptRule("RcvRule", {
131 ruleSetName: ruleSet.ruleSetName,
132 recipients: [domain],
133 scanEnabled: true,
134 actions: [
135 {
136 S3Action: {
137 // Reference the output (not the literal) so the rule
138 // deploys after the bucket + policy exist — SES validates
139 // the grant at createReceiptRule time.
140 BucketName: bucket.bucketName,
141 ObjectKeyPrefix: "inbound/",
142 },
143 },
144 ],
145 });
146 yield* ActiveReceiptRuleSet("RcvActive", {
147 ruleSetName: ruleSet.ruleSetName,
148 });
149 }),
150 );
151
152 // Wait for Easy DKIM detection (SES polls the published CNAMEs;
153 // typically 1-3 minutes with Cloudflare's fast propagation).
154 const verified = yield* sesv2.getEmailIdentity({ EmailIdentity: domain }).pipe(
155 Effect.repeat({
156 schedule: Schedule.spaced("10 seconds"),
157 until: (identity): boolean => identity.DkimAttributes?.Status === "SUCCESS",
158 times: 48,
159 }),
160 );
161 expect(verified.DkimAttributes?.Status).toBe("SUCCESS");
162
163 // The first delivery attempt can hard-bounce while SES inbound is
164 // still propagating the freshly activated rule set — and a hard
165 // bounce auto-adds the recipient to the ACCOUNT-level suppression
166 // list, silently swallowing every later send (the entry outlives
167 // stack.destroy(), so it would poison reruns too). Clear it before
168 // each attempt and re-send in bounded rounds until the marked
169 // message lands.
170 const unsuppress = sesv2
171 .deleteSuppressedDestination({ EmailAddress: recipient })
172 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
173
174 // A bounced first attempt also routes the MAILER-DAEMON bounce back
175 // through the rule into the bucket, so match the marker subject in
176 // the raw message rather than counting objects.
177 const findMarked = Effect.gen(function* () {
178 const listing = yield* s3.listObjectsV2({
179 Bucket: bucketName,
180 Prefix: "inbound/",
181 });
182 const keys = (listing.Contents ?? [])
183 .map((object) => object.Key!)
184 .filter((key) => !key.includes("AMAZON_SES_SETUP_NOTIFICATION"));
185 for (const key of keys) {
186 const raw = yield* s3
187 .getObject({ Bucket: bucketName, Key: key })
188 .pipe(Effect.flatMap((object) => Stream.mkString(Stream.decodeText(object.Body!))));
189 if (raw.includes(`Subject: ${SUBJECT_MARKER}`)) return raw;
190 }
191 return undefined;
192 });
193
194 const attemptDelivery = Effect.gen(function* () {
195 yield* unsuppress;
196 // Sandbox allows both legs because the domain identity is now
197 // verified; verification propagates eventually, so retry the typed
198 // MessageRejected briefly.
199 yield* sesv2
200 .sendEmail({
201 FromEmailAddress: `sender@${domain}`,
202 Destination: { ToAddresses: [recipient] },
203 Content: {
204 Simple: {
205 Subject: { Data: SUBJECT_MARKER },
206 Body: {
207 Text: { Data: "Round trip through SES email receiving." },
208 },
209 },
210 },
211 })
212 .pipe(
213 Effect.retry({
214 while: (error) => error._tag === "MessageRejected",
215 schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(12)]),
216 }),
217 );
218 return yield* findMarked.pipe(
219 Effect.repeat({
220 schedule: Schedule.spaced("5 seconds"),
221 until: (raw): boolean => raw !== undefined,
222 times: 12,
223 }),
224 );
225 });
226
227 const raw = yield* attemptDelivery.pipe(
228 Effect.repeat({
229 schedule: Schedule.spaced("5 seconds"),
230 until: (found): boolean => found !== undefined,
231 times: 4,
232 }),
233 );
234 expect(raw).toBeDefined();
235 expect(raw).toContain(`Subject: ${SUBJECT_MARKER}`);
236 expect(raw).toContain(`To: ${recipient}`);
237
238 yield* stack.destroy();
239 }).pipe(
240 Effect.ensuring(
241 Effect.all([
242 captured
243 ? ses.setActiveReceiptRuleSet({ RuleSetName: captured }).pipe(Effect.ignore)
244 : Effect.void,
245 // Leave the account suppression list the way we found it.
246 sesv2.deleteSuppressedDestination({ EmailAddress: recipient }).pipe(Effect.ignore),
247 ]),
248 ),
249 );
250 }),
251 {
252 tags: [
253 "provider:aws",
254 "provider:aws:s3",
255 "provider:aws:ses",
256 "provider:cloudflare",
257 "provider:cloudflare:dns",
258 "provider:cloudflare:zone",
259 "live",
260 ],
261 timeout: 900_000,
262 exclusive: "aws:ses-account",
263 },
264 );