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, 06:00 UTC
| 1 | import * as Lambda from "@alchemy.run/aws/Lambda"; |
| 2 | import * as SES from "@alchemy.run/aws/SES"; |
| 3 | import * as Output from "alchemy/Output"; |
| 4 | import * as Duration from "effect/Duration"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 7 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 8 | import * as Layer from "effect/Layer"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import path from "pathe"; |
| 11 | |
| 12 | const main = path.resolve(import.meta.dirname, "handler.ts"); |
| 13 | |
| 14 | // The SES mailbox simulator accepts mail even in the sandbox. |
| 15 | const SIMULATOR = "success@simulator.amazonses.com"; |
| 16 | |
| 17 | // The address the gated test starts verification FOR. SES authorizes |
| 18 | // ses:SendCustomVerificationEmail against the identity of the address in the |
| 19 | // request — the recipient — so the gated real-send test needs a binding scoped |
| 20 | // to that address, not to the template's sender. |
| 21 | // |
| 22 | // Referenced, never managed: no EmailIdentity resource is declared for it, so |
| 23 | // nothing adopts or destroys account state. Read at module load, which happens |
| 24 | // both locally at deploy and inside the Lambda, so it is forwarded as env. |
| 25 | const CVE_RECIPIENT = process.env.AWS_TEST_SES_CVE_RECIPIENT; |
| 26 | |
| 27 | export class SESTestFunction extends Lambda.Function<Lambda.Function>()("SESTestFunction") {} |
| 28 | |
| 29 | export default SESTestFunction.make( |
| 30 | { |
| 31 | main, |
| 32 | functionUrl: true, |
| 33 | timeout: Duration.seconds(30), |
| 34 | // The gate is read at module load, which happens BOTH locally at deploy |
| 35 | // (where the binding is declared) and inside the Lambda (where the client |
| 36 | // is constructed). Forward it so the deployed function sees the same |
| 37 | // value the deploy did. |
| 38 | ...(CVE_RECIPIENT ? { env: { AWS_TEST_SES_CVE_RECIPIENT: CVE_RECIPIENT } } : {}), |
| 39 | }, |
| 40 | Effect.gen(function* () { |
| 41 | // Domain identity — deterministic, never verified. In the SES sandbox a |
| 42 | // send from it fails with a typed MessageRejected; the ungated test |
| 43 | // asserts exactly that tag. A verified from-address can be supplied per |
| 44 | // request (?from=...) to exercise the success path. |
| 45 | const identity = yield* SES.EmailIdentity("SendIdentity", { |
| 46 | emailIdentity: "ses-bindings.alchemy-test.example.com", |
| 47 | }); |
| 48 | const configSet = yield* SES.ConfigurationSet("SendConfigSet", {}); |
| 49 | const template = yield* SES.EmailTemplate("SendTemplate", { |
| 50 | subject: "Hello, {{name}}!", |
| 51 | text: "Hi {{name}}.", |
| 52 | }); |
| 53 | |
| 54 | // Publish send/bounce/complaint events for this configuration set to the |
| 55 | // default EventBridge bus so `consumeEmailEvents` below has a producer. |
| 56 | yield* SES.ConfigurationSetEventDestination("ToEventBridge", { |
| 57 | configurationSetName: configSet.configurationSetName, |
| 58 | matchingEventTypes: ["SEND", "DELIVERY", "BOUNCE", "COMPLAINT"], |
| 59 | eventBridgeDestination: { |
| 60 | eventBusArn: Output.all(configSet.configurationSetArn).pipe( |
| 61 | Output.map(([arn]) => |
| 62 | arn |
| 63 | .replace(":ses:", ":events:") |
| 64 | .replace(/:configuration-set\/.*$/, ":event-bus/default"), |
| 65 | ), |
| 66 | ), |
| 67 | }, |
| 68 | }); |
| 69 | |
| 70 | // Event source: subscribe the host to SES email events. The deploy |
| 71 | // proves the EventBridge rule + invoke permission wiring; events only |
| 72 | // flow for real sends (gated behind AWS_TEST_SES_FROM in the tests). |
| 73 | yield* SES.consumeEmailEvents( |
| 74 | { kinds: ["send", "delivery", "bounce", "complaint"] }, |
| 75 | (events) => |
| 76 | Stream.runForEach(events, (event) => |
| 77 | Effect.log(`ses email event: ${event["detail-type"]} (${event.detail.mail?.messageId})`), |
| 78 | ), |
| 79 | ); |
| 80 | |
| 81 | // No custom verification email template is declared here: SES rejects |
| 82 | // CreateCustomVerificationEmailTemplate unless its FromEmailAddress is |
| 83 | // already a verified identity, which a bare account has none of, and a |
| 84 | // failed create here would take down every binding test in the file. The |
| 85 | // template name is a request parameter instead — see /send-custom-verification. |
| 86 | |
| 87 | const sendEmail = yield* SES.SendEmail(identity, configSet); |
| 88 | const sendWithoutConfigSet = yield* SES.SendEmail(identity); |
| 89 | const sendBulkEmail = yield* SES.SendBulkEmail(identity, configSet); |
| 90 | const renderTemplate = yield* SES.RenderEmailTemplate(template); |
| 91 | const getAccount = yield* SES.GetAccount(); |
| 92 | const suppress = yield* SES.PutSuppressedDestination(); |
| 93 | const getSuppressed = yield* SES.GetSuppressedDestination(); |
| 94 | const listSuppressed = yield* SES.ListSuppressedDestinations(); |
| 95 | const unsuppress = yield* SES.DeleteSuppressedDestination(); |
| 96 | const sendBounce = yield* SES.SendBounce(); |
| 97 | const sendCustomVerification = yield* SES.SendCustomVerificationEmail(identity, configSet); |
| 98 | // Scoped by REFERENCE to the address the gated test verifies. The binding |
| 99 | // above is scoped to the fixture's own (unverifiable) domain, so it can |
| 100 | // only ever authorize verification of addresses AT that domain — which is |
| 101 | // why the ungated test gets a request-level rejection there and this |
| 102 | // separate binding is needed for a real send. No ownership: the recipient |
| 103 | // is never declared as a resource. |
| 104 | const sendCustomVerificationVerified = CVE_RECIPIENT |
| 105 | ? yield* SES.SendCustomVerificationEmail({ |
| 106 | emailIdentity: CVE_RECIPIENT, |
| 107 | }) |
| 108 | : undefined; |
| 109 | const getMessageInsights = yield* SES.GetMessageInsights(); |
| 110 | const batchGetMetricData = yield* SES.BatchGetMetricData(); |
| 111 | const getDomainStatisticsReport = yield* SES.GetDomainStatisticsReport(); |
| 112 | const getBlacklistReports = yield* SES.GetBlacklistReports(); |
| 113 | const TemplateName = yield* template.templateName; |
| 114 | |
| 115 | return { |
| 116 | fetch: Effect.gen(function* () { |
| 117 | const request = yield* HttpServerRequest; |
| 118 | const url = new URL(request.originalUrl); |
| 119 | const pathname = url.pathname; |
| 120 | const from = url.searchParams.get("from") ?? undefined; |
| 121 | const to = url.searchParams.get("to") ?? SIMULATOR; |
| 122 | const email = url.searchParams.get("email") ?? undefined; |
| 123 | |
| 124 | const respond = <A extends object, E extends { _tag: string }>( |
| 125 | effect: Effect.Effect<A, E>, |
| 126 | pick: (result: A) => object, |
| 127 | ) => |
| 128 | effect.pipe( |
| 129 | Effect.flatMap((result) => HttpServerResponse.json(pick(result))), |
| 130 | Effect.catch((e) => |
| 131 | HttpServerResponse.json({ |
| 132 | error: e._tag, |
| 133 | message: "message" in e ? (e as { message?: string }).message : undefined, |
| 134 | }), |
| 135 | ), |
| 136 | ); |
| 137 | |
| 138 | if (request.method === "POST" && pathname === "/send-simple") { |
| 139 | return yield* respond( |
| 140 | sendEmail({ |
| 141 | FromEmailAddress: from, |
| 142 | Destination: { ToAddresses: [to] }, |
| 143 | Content: { |
| 144 | Simple: { |
| 145 | Subject: { Data: "alchemy SES binding test" }, |
| 146 | Body: { Text: { Data: "Hello from the SendEmail binding." } }, |
| 147 | }, |
| 148 | }, |
| 149 | }), |
| 150 | (result) => ({ messageId: result.MessageId }), |
| 151 | ); |
| 152 | } |
| 153 | |
| 154 | if (request.method === "POST" && pathname === "/send-template") { |
| 155 | const templateName = yield* TemplateName; |
| 156 | return yield* respond( |
| 157 | sendEmail({ |
| 158 | FromEmailAddress: from, |
| 159 | Destination: { ToAddresses: [to] }, |
| 160 | Content: { |
| 161 | Template: { |
| 162 | TemplateName: templateName, |
| 163 | TemplateData: JSON.stringify({ name: "Ada" }), |
| 164 | }, |
| 165 | }, |
| 166 | }), |
| 167 | (result) => ({ messageId: result.MessageId }), |
| 168 | ); |
| 169 | } |
| 170 | |
| 171 | if (request.method === "POST" && pathname === "/send-plain") { |
| 172 | return yield* respond( |
| 173 | sendWithoutConfigSet({ |
| 174 | FromEmailAddress: from, |
| 175 | Destination: { ToAddresses: [to] }, |
| 176 | Content: { |
| 177 | Simple: { |
| 178 | Subject: { Data: "alchemy SES binding test (no config set)" }, |
| 179 | Body: { Text: { Data: "Hello without a config set." } }, |
| 180 | }, |
| 181 | }, |
| 182 | }), |
| 183 | (result) => ({ messageId: result.MessageId }), |
| 184 | ); |
| 185 | } |
| 186 | |
| 187 | if (request.method === "POST" && pathname === "/send-bulk") { |
| 188 | const templateName = yield* TemplateName; |
| 189 | return yield* respond( |
| 190 | sendBulkEmail({ |
| 191 | FromEmailAddress: from, |
| 192 | DefaultContent: { |
| 193 | Template: { |
| 194 | TemplateName: templateName, |
| 195 | TemplateData: JSON.stringify({ name: "friend" }), |
| 196 | }, |
| 197 | }, |
| 198 | BulkEmailEntries: [ |
| 199 | { |
| 200 | Destination: { ToAddresses: [to] }, |
| 201 | ReplacementEmailContent: { |
| 202 | ReplacementTemplate: { |
| 203 | ReplacementTemplateData: JSON.stringify({ name: "Ada" }), |
| 204 | }, |
| 205 | }, |
| 206 | }, |
| 207 | ], |
| 208 | }), |
| 209 | (result) => ({ |
| 210 | results: (result.BulkEmailEntryResults ?? []).map((entry) => ({ |
| 211 | status: entry.Status, |
| 212 | messageId: entry.MessageId, |
| 213 | error: entry.Error, |
| 214 | })), |
| 215 | }), |
| 216 | ); |
| 217 | } |
| 218 | |
| 219 | if (request.method === "POST" && pathname === "/render-template") { |
| 220 | return yield* respond( |
| 221 | renderTemplate({ |
| 222 | TemplateData: JSON.stringify({ name: "Ada" }), |
| 223 | }), |
| 224 | (result) => ({ rendered: result.RenderedTemplate }), |
| 225 | ); |
| 226 | } |
| 227 | |
| 228 | if (request.method === "GET" && pathname === "/account") { |
| 229 | return yield* respond(getAccount(), (account) => ({ |
| 230 | sendingEnabled: account.SendingEnabled, |
| 231 | productionAccess: account.ProductionAccessEnabled, |
| 232 | max24HourSend: account.SendQuota?.Max24HourSend, |
| 233 | })); |
| 234 | } |
| 235 | |
| 236 | if (request.method === "POST" && pathname === "/suppress") { |
| 237 | return yield* respond(suppress({ EmailAddress: email!, Reason: "BOUNCE" }), () => ({ |
| 238 | suppressed: email, |
| 239 | })); |
| 240 | } |
| 241 | |
| 242 | if (request.method === "GET" && pathname === "/suppressed") { |
| 243 | return yield* respond(getSuppressed({ EmailAddress: email! }), (result) => ({ |
| 244 | email: result.SuppressedDestination.EmailAddress, |
| 245 | reason: result.SuppressedDestination.Reason, |
| 246 | })); |
| 247 | } |
| 248 | |
| 249 | if (request.method === "GET" && pathname === "/suppressed-list") { |
| 250 | return yield* respond( |
| 251 | listSuppressed({ Reasons: ["BOUNCE"], PageSize: 100 }), |
| 252 | (result) => ({ |
| 253 | emails: (result.SuppressedDestinationSummaries ?? []).map( |
| 254 | (summary) => summary.EmailAddress, |
| 255 | ), |
| 256 | }), |
| 257 | ); |
| 258 | } |
| 259 | |
| 260 | if (request.method === "POST" && pathname === "/unsuppress") { |
| 261 | return yield* respond(unsuppress({ EmailAddress: email! }), () => ({ |
| 262 | unsuppressed: email, |
| 263 | })); |
| 264 | } |
| 265 | |
| 266 | if (request.method === "POST" && pathname === "/send-bounce") { |
| 267 | // A fabricated message id when none is supplied — SES only accepts a |
| 268 | // bounce for a message it actually received within 24h, so the |
| 269 | // ungated test drives this path and asserts a typed rejection. Set |
| 270 | // ?messageId= to a real received message id to exercise the success |
| 271 | // path (gated behind AWS_TEST_SES_BOUNCE_MESSAGE_ID in the test). |
| 272 | const messageId = |
| 273 | url.searchParams.get("messageId") ?? |
| 274 | "00000000000000000000000000000000000000000000000000-0000"; |
| 275 | return yield* respond( |
| 276 | sendBounce({ |
| 277 | OriginalMessageId: messageId, |
| 278 | BounceSender: from ?? "mailer-daemon@ses-bindings.alchemy-test.example.com", |
| 279 | BouncedRecipientInfoList: [{ Recipient: to, BounceType: "DoesNotExist" }], |
| 280 | }), |
| 281 | (result) => ({ messageId: result.MessageId }), |
| 282 | ); |
| 283 | } |
| 284 | |
| 285 | if (request.method === "POST" && pathname === "/send-custom-verification") { |
| 286 | // The template name comes from the request: on a bare account no |
| 287 | // verified sender exists to create one with, so the ungated test |
| 288 | // passes a name that does not resolve and asserts the typed |
| 289 | // rejection. AWS_TEST_SES_CVE_TEMPLATE names a real one. |
| 290 | const templateName = url.searchParams.get("template") ?? "alchemy-test-missing-template"; |
| 291 | return yield* respond( |
| 292 | sendCustomVerification({ |
| 293 | EmailAddress: email ?? "verify-target@simulator.amazonses.com", |
| 294 | TemplateName: templateName, |
| 295 | }), |
| 296 | (result) => ({ messageId: result.MessageId }), |
| 297 | ); |
| 298 | } |
| 299 | |
| 300 | if (request.method === "POST" && pathname === "/send-custom-verification-verified") { |
| 301 | if (sendCustomVerificationVerified === undefined) { |
| 302 | return yield* HttpServerResponse.json( |
| 303 | { error: "AWS_TEST_SES_CVE_RECIPIENT not set at deploy time" }, |
| 304 | { status: 412 }, |
| 305 | ); |
| 306 | } |
| 307 | const templateName = url.searchParams.get("template") ?? "alchemy-test-missing-template"; |
| 308 | return yield* respond( |
| 309 | sendCustomVerificationVerified({ |
| 310 | EmailAddress: email ?? SIMULATOR, |
| 311 | TemplateName: templateName, |
| 312 | }), |
| 313 | (result) => ({ messageId: result.MessageId }), |
| 314 | ); |
| 315 | } |
| 316 | |
| 317 | if (request.method === "GET" && pathname === "/message-insights") { |
| 318 | // No real send backs a fabricated message id, so SES rejects it |
| 319 | // with a typed error (NotFoundException, or BadRequestException when |
| 320 | // VDM is disabled). Set ?messageId= to a real send's id to exercise |
| 321 | // the success path. |
| 322 | const messageId = |
| 323 | url.searchParams.get("messageId") ?? |
| 324 | "0000000000000000-00000000-0000-0000-0000-000000000000-000000"; |
| 325 | return yield* respond(getMessageInsights({ MessageId: messageId }), (result) => ({ |
| 326 | messageId: result.MessageId, |
| 327 | insights: result.Insights?.length ?? 0, |
| 328 | })); |
| 329 | } |
| 330 | |
| 331 | if (request.method === "POST" && pathname === "/metric-data") { |
| 332 | // SES rejects partial-day windows: "To get daily aggregated data |
| 333 | // you must not specify partial-day timestamps. Please make your |
| 334 | // interval go from midnight to midnight UTC." |
| 335 | // |
| 336 | // ?partialDay=1 deliberately sends such a window so a test can pin |
| 337 | // the typed rejection independently of whether VDM is enabled. |
| 338 | const partialDay = url.searchParams.get("partialDay") !== null; |
| 339 | const end = new Date(); |
| 340 | if (!partialDay) end.setUTCHours(0, 0, 0, 0); |
| 341 | const start = new Date(end.getTime() - 7 * 24 * 3600 * 1000); |
| 342 | return yield* respond( |
| 343 | batchGetMetricData({ |
| 344 | Queries: [ |
| 345 | { |
| 346 | Id: "sends", |
| 347 | Namespace: "VDM", |
| 348 | Metric: "SEND", |
| 349 | StartDate: start, |
| 350 | EndDate: end, |
| 351 | }, |
| 352 | ], |
| 353 | }), |
| 354 | (result) => ({ results: (result.Results ?? []).length }), |
| 355 | ); |
| 356 | } |
| 357 | |
| 358 | if (request.method === "GET" && pathname === "/domain-statistics") { |
| 359 | const domain = url.searchParams.get("domain") ?? "ses-bindings.alchemy-test.example.com"; |
| 360 | const end = new Date(); |
| 361 | const start = new Date(end.getTime() - 7 * 24 * 3600 * 1000); |
| 362 | return yield* respond( |
| 363 | getDomainStatisticsReport({ |
| 364 | Domain: domain, |
| 365 | StartDate: start, |
| 366 | EndDate: end, |
| 367 | }), |
| 368 | (result) => ({ days: result.DailyVolumes.length }), |
| 369 | ); |
| 370 | } |
| 371 | |
| 372 | if (request.method === "GET" && pathname === "/blacklist-reports") { |
| 373 | const ip = url.searchParams.get("ip") ?? "192.0.2.1"; |
| 374 | return yield* respond(getBlacklistReports({ BlacklistItemNames: [ip] }), (result) => ({ |
| 375 | ips: Object.keys(result.BlacklistReport), |
| 376 | })); |
| 377 | } |
| 378 | |
| 379 | if (request.method === "GET" && pathname === "/health") { |
| 380 | return HttpServerResponse.text("ok"); |
| 381 | } |
| 382 | |
| 383 | return yield* HttpServerResponse.json( |
| 384 | { error: "Not found", method: request.method, pathname }, |
| 385 | { status: 404 }, |
| 386 | ); |
| 387 | }).pipe(Effect.orDie), |
| 388 | }; |
| 389 | }).pipe( |
| 390 | Effect.provide( |
| 391 | Layer.mergeAll( |
| 392 | Lambda.EventSource, |
| 393 | SES.SendEmailHttp, |
| 394 | SES.SendBulkEmailHttp, |
| 395 | SES.RenderEmailTemplateHttp, |
| 396 | SES.GetAccountHttp, |
| 397 | SES.PutSuppressedDestinationHttp, |
| 398 | SES.GetSuppressedDestinationHttp, |
| 399 | SES.ListSuppressedDestinationsHttp, |
| 400 | SES.DeleteSuppressedDestinationHttp, |
| 401 | SES.SendBounceHttp, |
| 402 | SES.SendCustomVerificationEmailHttp, |
| 403 | SES.GetMessageInsightsHttp, |
| 404 | SES.BatchGetMetricDataHttp, |
| 405 | SES.GetDomainStatisticsReportHttp, |
| 406 | SES.GetBlacklistReportsHttp, |
| 407 | ), |
| 408 | ), |
| 409 | ), |
| 410 | ); |