diff --git a/README.md b/README.md index 248f9c4d63e..c30910445be 100644 --- a/README.md +++ b/README.md @@ -256,11 +256,14 @@ During development, the dummy email transporter writes emails to a local folder. - `DUMMY_EMAIL_TRANSPORTER_FILE_PATH`: Default is `var/api/dummy-email-transporter/email-dumps.yml` - `SYSTEM_EMAIL_SENDER_NAME`: the display name for the email sender (required if transport is `aws` or `smtp`) - `SYSTEM_EMAIL_ADDRESS`: the email address for the email sender (required if transport is `aws` or `smtp`) +- `HASH_FLOW_EMAIL_SENDER`: the address the AI worker sends flow emails from (required on the worker if transporter is `aws` or `smtp`) - `SMTP_SERVER_HOST`: the host for a SMTP server (required if transporter is `smtp`) - `SMTP_SERVER_PORT`: the port for a SMTP server (required if transporter is `smtp`) - `SMTP_SERVER_USERNAME`: auth username for SMTP server (optional if API is automatically authenticated) - `SMTP_SERVER_PASSWORD`: password for SMTP server (optional if API is automatically authenticated) +The AI worker reads `HASH_EMAIL_TRANSPORTER`, `HASH_FLOW_EMAIL_SENDER` and the `SMTP_SERVER_*` variables for the Send email flow action, and none of the `SYSTEM_EMAIL_*` ones. Without a transporter, or without a sender for `aws` or `smtp`, a Send email step fails. With `dummy`, which the worker only uses in development and tests, it writes emails to `var/ai-worker/dummy-email-transporter/email-dumps.yml`. Unless `ENVIRONMENT` is `production`, the worker only sends to `@hash.ai` addresses. + #### Postgres - `POSTGRES_PORT` (default: `5432`) diff --git a/apps/hash-ai-worker-ts/scripts/flow-scenarios/scenarios/send-email.scenario.ts b/apps/hash-ai-worker-ts/scripts/flow-scenarios/scenarios/send-email.scenario.ts new file mode 100644 index 00000000000..d42debe56aa --- /dev/null +++ b/apps/hash-ai-worker-ts/scripts/flow-scenarios/scenarios/send-email.scenario.ts @@ -0,0 +1,101 @@ +import { typedActionDefinitions as actions } from "@local/hash-isomorphic-utils/flows/action-definitions"; +import { + constant, + defineFlow, + flowInput, +} from "@local/hash-isomorphic-utils/flows/define-flow"; + +import { defineScenario } from "../scenario.js"; + +const composedFlow = defineFlow( + { + flowDefinitionId: "00000000-0000-4000-8000-000000001832", + name: "Send email run", + description: "Send an email with a typed body to an address from an input", + inputs: { + to: flowInput("Text"), + subject: flowInput("Text"), + }, + }, + ({ inputs, step }) => { + const send = step("send", actions.sendEmail, { + description: "Send the email", + inputs: { + to: inputs.to, + subject: inputs.subject, + body: constant( + "Text", + "Hi Ada,\n\nYour order <#1832> has shipped & is on its way.\n\nThanks!", + ), + }, + }); + + return { outputs: { messageId: send.outputs.messageId } }; + }, +); + +const draftedFlow = defineFlow( + { + flowDefinitionId: "00000000-0000-4000-8000-000000001833", + name: "Draft and send email run", + description: "Draft an email with AI and send its subject and body", + inputs: {}, + }, + ({ step }) => { + const draft = step("draft", actions.draftMessage, { + description: "Draft the email", + inputs: { + instructions: constant( + "Text", + "Tell Ada, in two sentences, that her order has shipped. Sign off as the HASH team.", + ), + }, + }); + + const send = step("send", actions.sendEmail, { + description: "Send the draft", + inputs: { + to: constant("Text", "ada@hash.ai"), + subject: draft.outputs.subject, + body: draft.outputs.body, + replyTo: constant("Text", "grace@hash.ai"), + }, + }); + + return { outputs: { messageId: send.outputs.messageId } }; + }, +); + +/** + * The ID an email is given is different each time, so the runs expect statuses rather than outputs. With the worker's + * `dummy` transporter, the emails are written to `var/ai-worker/dummy-email-transporter/email-dumps.yml`, with the + * sender, Reply-to and ID of each. + */ +export const scenario = defineScenario({ + name: "Send email", + purpose: + "Sends an email composed from flow inputs and a typed body, sends one whose subject and body Draft message wrote, and refuses a recipient outside hash.ai, which only production may email.", + runs: [ + { + flow: composedFlow, + inputs: { + to: { kind: "Text", value: "ada@hash.ai" }, + subject: { kind: "Text", value: "Your order has shipped" }, + }, + expect: { steps: { send: {} } }, + }, + { + flow: draftedFlow, + inputs: {}, + expect: { steps: { draft: {}, send: {} } }, + }, + { + flow: composedFlow, + inputs: { + to: { kind: "Text", value: "ada@example.com" }, + subject: { kind: "Text", value: "Your order has shipped" }, + }, + expect: { status: "FAILED", steps: { send: { status: "FAILED" } } }, + }, + ], +}); diff --git a/apps/hash-ai-worker-ts/src/activities/flow-activities.ts b/apps/hash-ai-worker-ts/src/activities/flow-activities.ts index f7a844e124b..1947b64cae7 100644 --- a/apps/hash-ai-worker-ts/src/activities/flow-activities.ts +++ b/apps/hash-ai-worker-ts/src/activities/flow-activities.ts @@ -24,6 +24,7 @@ import { planDashboardRefinementAction } from "./flow-activities/plan-dashboard- import { processAutomaticBrowsingSettingsAction } from "./flow-activities/process-automatic-browsing-settings-action.js"; import { queryEntitiesAction } from "./flow-activities/query-entities-action.js"; import { researchEntitiesAction } from "./flow-activities/research-entities-action.js"; +import { sendEmailAction } from "./flow-activities/send-email-action.js"; import { takeFirstAction } from "./flow-activities/take-first-action.js"; import { updateEntityAction } from "./flow-activities/update-entity-action.js"; import { webSearchAction } from "./flow-activities/web-search-action.js"; @@ -60,6 +61,7 @@ export const createFlowActionActivities: CreateFlowActivities< processAutomaticBrowsingSettingsAction, queryEntitiesAction, researchEntitiesAction, + sendEmailAction, takeFirstAction, updateEntityAction, webSearchAction, diff --git a/apps/hash-ai-worker-ts/src/activities/flow-activities/send-email-action.test.ts b/apps/hash-ai-worker-ts/src/activities/flow-activities/send-email-action.test.ts new file mode 100644 index 00000000000..30e05b6eba1 --- /dev/null +++ b/apps/hash-ai-worker-ts/src/activities/flow-activities/send-email-action.test.ts @@ -0,0 +1,301 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { EmailSendError } from "@local/hash-backend-utils/email"; +import { StatusCode } from "@local/status"; + +import { getFlowContext } from "../shared/get-flow-context.js"; +import { sendEmailAction } from "./send-email-action.js"; +import { getEmailTransporter } from "./send-email-action/get-email-transporter.js"; +import { getUserEmail } from "./send-email-action/get-user-email.js"; + +import type { EmailSendFailureOutcome } from "@local/hash-backend-utils/email"; +import type { StepInput } from "@local/hash-isomorphic-utils/flows/types"; + +vi.mock("../shared/get-flow-context.js", () => ({ getFlowContext: vi.fn() })); +vi.mock("./send-email-action/get-user-email.js", () => ({ + getUserEmail: vi.fn(), +})); +vi.mock("./send-email-action/get-email-transporter.js", () => ({ + getEmailTransporter: vi.fn(), +})); + +const currentContext = vi.hoisted(() => vi.fn()); + +vi.mock("@temporalio/activity", () => ({ + Context: { current: currentContext }, +})); + +const onAttempt = (attempt: number) => + currentContext.mockReturnValue({ info: { attempt }, log: { warn: vi.fn() } }); + +const sendMail = vi.fn(); + +const startedBy = (run: { flowTriggerEntityId?: string }) => + vi.mocked(getFlowContext).mockResolvedValue({ + userAuthentication: { actorId: "starter" }, + ...run, + } as Awaited>); + +beforeEach(() => { + vi.stubEnv("ENVIRONMENT", "staging"); + + sendMail.mockReset().mockResolvedValue({ messageId: "ses-message-id" }); + vi.mocked(getEmailTransporter).mockReset().mockReturnValue({ sendMail }); + onAttempt(1); + vi.mocked(getUserEmail).mockReset().mockResolvedValue("starter@example.com"); + startedBy({}); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + vi.useRealTimers(); +}); + +const run = ( + params: { + to?: string; + subject?: string; + body?: string; + replyTo?: string; + } = {}, +) => + sendEmailAction({ + inputs: Object.entries({ + to: "ada@hash.ai", + subject: "Your order", + body: "Hi Ada,\n\nThanks!", + ...params, + }).map(([inputName, value]): StepInput => ({ + inputName, + payload: { kind: "Text", value }, + })), + }); + +const sent = { + code: StatusCode.Ok, + contents: [ + { + outputs: [ + { + outputName: "messageId", + payload: { kind: "Text", value: "ses-message-id" }, + }, + ], + }, + ], +}; + +describe("sendEmailAction", () => { + it("sends the body as plain text, with replies going to the person who started the run", async () => { + await expect( + run({ + body: `Hi Ada & "co",\r\n\nSee `, + }), + ).resolves.toEqual(sent); + + expect(getUserEmail).toHaveBeenCalledWith("starter"); + expect(sendMail).toHaveBeenCalledExactlyOnceWith({ + to: "ada@hash.ai", + replyTo: "starter@example.com", + subject: "Your order", + text: `Hi Ada & "co",\r\n\nSee `, + html: "Hi <b>Ada</b> & "co",

See <script>alert('1')</script>", + }); + }); + + it("sends replies to the address given instead, without looking up who started the run", async () => { + await expect(run({ replyTo: " grace@example.com " })).resolves.toEqual( + sent, + ); + + expect(sendMail.mock.calls[0]![0]).toMatchObject({ + replyTo: "grace@example.com", + }); + expect(getUserEmail).not.toHaveBeenCalled(); + }); + + it("keeps the subject on one line, so that it can't add a header", async () => { + await run({ subject: "Your order\r\nBcc: eve@example.com" }); + + expect(sendMail.mock.calls[0]![0]).toMatchObject({ + subject: "Your order Bcc: eve@example.com", + }); + }); + + it.each([ + ["more than one recipient", { to: "eve@example.com, ada@hash.ai" }], + ["an empty subject", { subject: " \n " }], + ["an empty body", { body: " " }], + ])("fails without sending for %s", async (_, params) => { + await expect(run(params)).resolves.toMatchObject({ + code: StatusCode.InvalidArgument, + }); + + expect(sendMail).not.toHaveBeenCalled(); + }); + + describe("outside production", () => { + it.each(["ada@example.com", "ada@nothash.ai"])( + "doesn't send to %s", + async (to) => { + await expect(run({ to })).resolves.toMatchObject({ + code: StatusCode.PermissionDenied, + }); + + expect(sendMail).not.toHaveBeenCalled(); + }, + ); + + it("doesn't send to another domain in an environment that doesn't say which it is", async () => { + vi.stubEnv("ENVIRONMENT", undefined); + + await expect(run({ to: "ada@example.com" })).resolves.toMatchObject({ + code: StatusCode.PermissionDenied, + }); + }); + + it("sends to a hash.ai address however its domain is written", async () => { + await expect(run({ to: "Ada@HASH.ai" })).resolves.toEqual(sent); + }); + }); + + it("sends to any domain in production", async () => { + vi.stubEnv("ENVIRONMENT", "production"); + + await expect(run({ to: "ada@example.com" })).resolves.toEqual(sent); + }); + + describe("in a run a schedule started", () => { + beforeEach(() => { + startedBy({ flowTriggerEntityId: "schedule" }); + }); + + it("fails without sending unless given a Reply-to, as nobody started the run", async () => { + await expect(run()).resolves.toMatchObject({ + code: StatusCode.FailedPrecondition, + message: expect.stringContaining("Reply-to") as string, + }); + + expect(sendMail).not.toHaveBeenCalled(); + }); + + it("sends with the Reply-to given", async () => { + await expect(run({ replyTo: "grace@example.com" })).resolves.toEqual( + sent, + ); + }); + }); + + it("fails when the worker has no email transporter", async () => { + vi.mocked(getEmailTransporter).mockReturnValue(null); + + await expect(run()).resolves.toMatchObject({ + code: StatusCode.FailedPrecondition, + }); + }); + + /* Thrown, it would make Temporal start another attempt, which reports that the email may have been sent. */ + it("fails when the worker's email settings are incomplete", async () => { + vi.mocked(getEmailTransporter).mockImplementation(() => { + throw new Error("Environment variable AWS_REGION is not set"); + }); + + await expect(run()).resolves.toMatchObject({ + code: StatusCode.FailedPrecondition, + message: expect.stringContaining("AWS_REGION") as string, + }); + }); + + describe("when the send fails", () => { + const sendFailure = (outcome: EmailSendFailureOutcome) => + new EmailSendError(outcome, new Error("SES said no")); + + /** Runs the step through the waits between its tries. */ + const runThroughTries = async () => { + vi.useFakeTimers(); + + const result = run(); + + await vi.runAllTimersAsync(); + + return result; + }; + + it("tries again within the attempt when the email wasn't sent but may be later", async () => { + sendMail.mockRejectedValueOnce(sendFailure("unavailable")); + + await expect(runThroughTries()).resolves.toEqual(sent); + + expect(sendMail).toHaveBeenCalledTimes(2); + }); + + it("fails the step, rather than throwing for another attempt, when three tries didn't send the email", async () => { + sendMail.mockRejectedValue(sendFailure("unavailable")); + + await expect(runThroughTries()).resolves.toMatchObject({ + code: StatusCode.Unavailable, + message: "The email wasn't sent: SES said no", + }); + + expect(sendMail).toHaveBeenCalledTimes(3); + }); + + it("fails the step without trying again when the provider refused the email", async () => { + sendMail.mockRejectedValue(sendFailure("rejected")); + + await expect(runThroughTries()).resolves.toMatchObject({ + code: StatusCode.FailedPrecondition, + message: "The email wasn't sent: SES said no", + }); + + expect(sendMail).toHaveBeenCalledTimes(1); + }); + + it.each([ + ["the provider may have accepted the email", sendFailure("unknown")], + ["the transporter throws something else", new Error("socket hang up")], + ])( + "fails the step without trying again, saying the email may have been sent, when %s", + async (_, error) => { + sendMail.mockRejectedValue(error); + + await expect(runThroughTries()).resolves.toMatchObject({ + code: StatusCode.Unknown, + message: expect.stringContaining("may have been sent") as string, + }); + + /* A second try could send the email twice. */ + expect(sendMail).toHaveBeenCalledTimes(1); + }, + ); + + it("tries again when looking up who started the run fails, and fails the step without sending if it keeps failing", async () => { + vi.mocked(getUserEmail).mockRejectedValueOnce( + new Error("Graph unavailable"), + ); + + await expect(runThroughTries()).resolves.toEqual(sent); + + vi.mocked(getUserEmail).mockRejectedValue(new Error("Graph unavailable")); + sendMail.mockClear(); + + await expect(runThroughTries()).resolves.toMatchObject({ + code: StatusCode.Unavailable, + message: "The email wasn't sent: Graph unavailable", + }); + + expect(sendMail).not.toHaveBeenCalled(); + }); + }); + + it("doesn't send on a later attempt, as the one before may have sent the email", async () => { + onAttempt(2); + + await expect(run()).resolves.toMatchObject({ + code: StatusCode.Unknown, + message: expect.stringContaining("may have been sent") as string, + }); + + expect(sendMail).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/hash-ai-worker-ts/src/activities/flow-activities/send-email-action.ts b/apps/hash-ai-worker-ts/src/activities/flow-activities/send-email-action.ts new file mode 100644 index 00000000000..e0c62205929 --- /dev/null +++ b/apps/hash-ai-worker-ts/src/activities/flow-activities/send-email-action.ts @@ -0,0 +1,225 @@ +import { Context } from "@temporalio/activity"; +import { backOff } from "exponential-backoff"; +import escape from "lodash/escape.js"; + +import { EmailSendError } from "@local/hash-backend-utils/email"; +import { getSimplifiedFlowActionInputs } from "@local/hash-isomorphic-utils/flows/action-definitions"; +import { validateEmailAddress } from "@local/hash-isomorphic-utils/flows/email-address"; +import { StatusCode } from "@local/status"; + +import { getFlowContext } from "../shared/get-flow-context.js"; +import { getEmailTransporter } from "./send-email-action/get-email-transporter.js"; +import { getUserEmail } from "./send-email-action/get-user-email.js"; + +import type { FlowActionActivity } from "@local/hash-backend-utils/flows"; +import type { FlowActionStepOutput } from "@local/hash-isomorphic-utils/flows/action-definitions"; +import type { Status } from "@local/status"; + +/** + * The only domain emails can be sent to unless `ENVIRONMENT` is `production`, so that a deployment that doesn't say + * which it is can't email anyone outside HASH. + */ +const restrictedRecipientDomain = "hash.ai"; + +const failure = (code: StatusCode, message: string): Status => ({ + code, + message, + contents: [], +}); + +const messageOf = (error: unknown) => + error instanceof Error ? error.message : String(error); + +const notSetUp = "This HASH instance isn't set up to send emails from flows"; + +const maxTries = 3; + +/** + * Runs `action` up to three times, a second and then two apart, for as long as `retryable` says its failure left the + * email unsent, as any failure before the send does. The tries are within one attempt of the step, as only its first + * attempt sends. + */ +const tryWhileNotSent = ( + action: () => Promise, + retryable: (error: unknown) => boolean = () => true, +) => + backOff(action, { + numOfAttempts: maxTries, + startingDelay: 1_000, + retry: (error: unknown, triesMade) => { + if (!retryable(error)) { + return false; + } + + Context.current().log.warn( + `Send email: try ${triesMade} of ${maxTries} didn't send the email: ${messageOf(error)}`, + ); + + return true; + }, + }); + +/** + * The body as HTML, escaped: it can come from a model or an entity, so none of it is sent as markup. Its line breaks + * are `
`s, as not every email client keeps them for `white-space`. + */ +const plainTextToHtml = (text: string) => + escape(text).replace(/\r\n?|\n/g, "
"); + +/** + * Sends one plain-text email to one address and returns the ID the provider gave it. Replies go to the address given, + * or to the person who started the run. + * + * SES can't tell an email it is sent again from a new one, so the step never sends an email that may already have been + * sent: + * - Only the step's first attempt sends. Temporal starts another when one times out or its worker stops, which can be + * after SES took the email, so a later attempt fails the step saying the email may have been sent. + * - A send that failed before SES took the email (it was unreachable or throttling) is tried again within the attempt. + * - An email the provider refused fails the step. + * - A send that ended without an answer fails the step saying the email may have been sent. + */ +export const sendEmailAction: FlowActionActivity<"sendEmail"> = async ({ + inputs, +}) => { + const { + to: toInput, + subject: subjectInput, + body, + replyTo: replyToInput, + } = getSimplifiedFlowActionInputs({ inputs, actionType: "sendEmail" }); + + const to = toInput.trim(); + /* A subject is one line, so that a line break can't add headers to the email. */ + const subject = subjectInput.replace(/\s+/g, " ").trim(); + /* A blank Reply-to, e.g. an optional flow input left empty, is one that wasn't given. */ + const trimmedReplyTo = replyToInput?.trim(); + const givenReplyTo = trimmedReplyTo === "" ? undefined : trimmedReplyTo; + + const invalidInput = + validateEmailAddress(to) ?? + (givenReplyTo ? validateEmailAddress(givenReplyTo) : undefined) ?? + (!subject ? "The subject is empty." : undefined) ?? + (!body.trim() ? "The body is empty." : undefined); + + if (invalidInput) { + return failure(StatusCode.InvalidArgument, invalidInput); + } + + if ( + process.env.ENVIRONMENT !== "production" && + !to.toLowerCase().endsWith(`@${restrictedRecipientDomain}`) + ) { + return failure( + StatusCode.PermissionDenied, + `Emails can only be sent to @${restrictedRecipientDomain} addresses in this environment, so not to ${to}.`, + ); + } + + if (Context.current().info.attempt > 1) { + return failure( + StatusCode.Unknown, + "The email may have been sent: an earlier attempt of this step ended without finishing. It wasn't sent again, to avoid sending it twice.", + ); + } + + let emailTransporter: ReturnType; + + try { + emailTransporter = getEmailTransporter(); + } catch (error) { + return failure( + StatusCode.FailedPrecondition, + `${notSetUp}: ${messageOf(error)}`, + ); + } + + if (!emailTransporter) { + return failure( + StatusCode.FailedPrecondition, + `${notSetUp}: its AI worker needs an email transporter (HASH_EMAIL_TRANSPORTER) and a sender (HASH_FLOW_EMAIL_SENDER).`, + ); + } + + let replyTo = givenReplyTo; + + if (!replyTo) { + try { + const { flowTriggerEntityId, userAuthentication } = + await tryWhileNotSent(getFlowContext); + + if (flowTriggerEntityId) { + return failure( + StatusCode.FailedPrecondition, + "A scheduled run has no person who started it for replies to go to. Give the step a Reply-to address.", + ); + } + + replyTo = await tryWhileNotSent(() => + getUserEmail(userAuthentication.actorId), + ); + } catch (error) { + return failure( + StatusCode.Unavailable, + `The email wasn't sent: ${messageOf(error)}`, + ); + } + } + + if (!replyTo) { + return failure( + StatusCode.FailedPrecondition, + "The person who started the run has no email address for replies to go to. Give the step a Reply-to address.", + ); + } + + const email = { + to, + replyTo, + subject, + text: body, + html: plainTextToHtml(body), + }; + + try { + const { messageId } = await tryWhileNotSent( + () => emailTransporter.sendMail(email), + (error) => + error instanceof EmailSendError && error.outcome === "unavailable", + ); + + return { + code: StatusCode.Ok, + contents: [ + { + outputs: [ + { + outputName: "messageId", + payload: { kind: "Text", value: messageId }, + }, + ] satisfies FlowActionStepOutput<"sendEmail">[], + }, + ], + }; + } catch (error) { + const outcome = error instanceof EmailSendError ? error.outcome : "unknown"; + const reason = messageOf(error); + + switch (outcome) { + case "unavailable": + return failure( + StatusCode.Unavailable, + `The email wasn't sent: ${reason}`, + ); + case "rejected": + return failure( + StatusCode.FailedPrecondition, + `The email wasn't sent: ${reason}`, + ); + case "unknown": + return failure( + StatusCode.Unknown, + `The email may have been sent: sending it ended without an answer (${reason}). It wasn't sent again, to avoid sending it twice.`, + ); + } + } +}; diff --git a/apps/hash-ai-worker-ts/src/activities/flow-activities/send-email-action/get-email-transporter.test.ts b/apps/hash-ai-worker-ts/src/activities/flow-activities/send-email-action/get-email-transporter.test.ts new file mode 100644 index 00000000000..601270570f3 --- /dev/null +++ b/apps/hash-ai-worker-ts/src/activities/flow-activities/send-email-action/get-email-transporter.test.ts @@ -0,0 +1,82 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +const createEmailTransporter = vi.hoisted(() => vi.fn()); + +vi.mock("@local/hash-backend-utils/email", () => ({ createEmailTransporter })); +vi.mock("../../../shared/logger.js", () => ({ logger: {} })); + +const transporter = { sendMail: vi.fn() }; + +/** The transporter of a worker started with these settings: the worker creates it once. */ +const getEmailTransporterWith = async ( + env: Record, +) => { + for (const [name, value] of Object.entries(env)) { + vi.stubEnv(name, value); + } + + vi.resetModules(); + createEmailTransporter.mockReset().mockReturnValue(transporter); + + const { getEmailTransporter } = await import("./get-email-transporter.js"); + + return getEmailTransporter(); +}; + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +describe("getEmailTransporter", () => { + /* The dummy transporter sends nothing, so a step in a deployment that used it would report emails as sent. */ + it("has no transporter in a deployment set to the dummy one", async () => { + await expect( + getEmailTransporterWith({ + HASH_EMAIL_TRANSPORTER: "dummy", + NODE_ENV: "production", + }), + ).resolves.toBeNull(); + + expect(createEmailTransporter).not.toHaveBeenCalled(); + }); + + /* Without a sender of its own, the shared transporter would look for the API's `SYSTEM_EMAIL_*` settings. */ + it.each([undefined, ""])( + "has no transporter in a deployment that sends when its sender is %j", + async (sender) => { + await expect( + getEmailTransporterWith({ + HASH_EMAIL_TRANSPORTER: "aws", + NODE_ENV: "production", + HASH_FLOW_EMAIL_SENDER: sender, + }), + ).resolves.toBeNull(); + + expect(createEmailTransporter).not.toHaveBeenCalled(); + }, + ); + + it("sends from the address HASH_FLOW_EMAIL_SENDER names", async () => { + await expect( + getEmailTransporterWith({ + HASH_EMAIL_TRANSPORTER: "aws", + NODE_ENV: "production", + HASH_FLOW_EMAIL_SENDER: "flows@example.com", + }), + ).resolves.toBe(transporter); + + expect(createEmailTransporter).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ from: "flows@example.com" }), + ); + }); + + it("uses the dummy transporter in development without a sender", async () => { + await expect( + getEmailTransporterWith({ + HASH_EMAIL_TRANSPORTER: "dummy", + NODE_ENV: "development", + HASH_FLOW_EMAIL_SENDER: undefined, + }), + ).resolves.toBe(transporter); + }); +}); diff --git a/apps/hash-ai-worker-ts/src/activities/flow-activities/send-email-action/get-email-transporter.ts b/apps/hash-ai-worker-ts/src/activities/flow-activities/send-email-action/get-email-transporter.ts new file mode 100644 index 00000000000..40b7856aa96 --- /dev/null +++ b/apps/hash-ai-worker-ts/src/activities/flow-activities/send-email-action/get-email-transporter.ts @@ -0,0 +1,42 @@ +import { createEmailTransporter } from "@local/hash-backend-utils/email"; + +import { logger } from "../../../shared/logger.js"; + +import type { EmailTransporter } from "@local/hash-backend-utils/email"; + +/** Well within the 5 minutes an attempt has, so a send that hangs fails the attempt itself, not Temporal's timeout. */ +const sendTimeout = { connectionTimeoutMs: 10_000, responseTimeoutMs: 60_000 }; + +let emailTransporter: EmailTransporter | null | undefined; + +/** + * The worker's email transporter, created on first use so that a worker without email settings still starts. Flow + * emails are from `HASH_FLOW_EMAIL_SENDER`. + * + * - `dummy` sends nothing, so a deployment ignores it rather than report emails as sent. It has a sender of its own. + * - `aws` and `smtp` need the sender: without one, the shared transporter looks for the API's `SYSTEM_EMAIL_*` settings. + * + * @returns `null` if `HASH_EMAIL_TRANSPORTER` names no transporter the worker can use, or a sender is missing. + */ +export const getEmailTransporter = (): EmailTransporter | null => { + if (emailTransporter === undefined) { + const sender = process.env.HASH_FLOW_EMAIL_SENDER; + + const canSend = + process.env.HASH_EMAIL_TRANSPORTER === "dummy" + ? process.env.NODE_ENV !== "production" + : !!sender; + + emailTransporter = canSend + ? createEmailTransporter({ + logger, + from: sender, + dummyFilePath: + "var/ai-worker/dummy-email-transporter/email-dumps.yml", + singleAttempt: sendTimeout, + }) + : null; + } + + return emailTransporter; +}; diff --git a/apps/hash-ai-worker-ts/src/activities/flow-activities/send-email-action/get-user-email.ts b/apps/hash-ai-worker-ts/src/activities/flow-activities/send-email-action/get-user-email.ts new file mode 100644 index 00000000000..18b87114fcf --- /dev/null +++ b/apps/hash-ai-worker-ts/src/activities/flow-activities/send-email-action/get-user-email.ts @@ -0,0 +1,45 @@ +import { queryEntities } from "@local/hash-graph-sdk/entity"; +import { currentTimeInstantTemporalAxes } from "@local/hash-isomorphic-utils/graph-queries"; +import { systemEntityTypes } from "@local/hash-isomorphic-utils/ontology-type-ids"; + +import { graphApiClient } from "../../shared/graph-api-client.js"; + +import type { UserId } from "@blockprotocol/type-system"; +import type { User } from "@local/hash-isomorphic-utils/system-types/shared"; + +/** + * The first email address of a user, read from their `User` entity as that user: the graph only gives a user's + * addresses to the user themselves. + * + * @returns `undefined` if the user has no `User` entity. + */ +export const getUserEmail = async ( + userId: UserId, +): Promise => { + const { + entities: [user], + } = await queryEntities( + { graphApi: graphApiClient }, + { actorId: userId }, + { + filter: { + all: [ + { + equal: [ + { path: ["type", "baseUrl"] }, + { parameter: systemEntityTypes.user.entityTypeBaseUrl }, + ], + }, + /* A user's entity is in their own web, with their ID as its uuid. */ + { equal: [{ path: ["webId"] }, { parameter: userId }] }, + { equal: [{ path: ["uuid"] }, { parameter: userId }] }, + ], + }, + temporalAxes: currentTimeInstantTemporalAxes, + includeDrafts: false, + includePermissions: false, + }, + ); + + return user?.properties["https://hash.ai/@h/types/property-type/email/"][0]; +}; diff --git a/apps/hash-ai-worker-ts/src/activities/shared/get-flow-context.ts b/apps/hash-ai-worker-ts/src/activities/shared/get-flow-context.ts index 71de562e8c7..2944bef613c 100644 --- a/apps/hash-ai-worker-ts/src/activities/shared/get-flow-context.ts +++ b/apps/hash-ai-worker-ts/src/activities/shared/get-flow-context.ts @@ -32,6 +32,7 @@ let _temporalClient: TemporalClient | undefined; type AiWorkflowParams = { createEntitiesAsDraft: boolean; dataSources: FlowDataSources; + flowTriggerEntityId?: EntityId; userAuthentication: { actorId: UserId }; webId: WebId; }; @@ -105,6 +106,7 @@ const getAiWorkflowParams = async (params: { const aiParams: AiWorkflowParams = { createEntitiesAsDraft, dataSources: runFlowWorkflowParams.dataSources, + flowTriggerEntityId: runFlowWorkflowParams.flowTriggerEntityId, userAuthentication: runFlowWorkflowParams.userAuthentication, webId: runFlowWorkflowParams.webId, }; @@ -117,6 +119,8 @@ type FlowContext = { createEntitiesAsDraft: boolean; dataSources: FlowDataSources; flowEntityId: EntityId; + /** The `Flow Trigger` entity that started the run, e.g. a `Flow Schedule`. Unset for a run a person started. */ + flowTriggerEntityId?: EntityId; runId: string; stepId: string; userAuthentication: { actorId: UserId }; @@ -146,10 +150,15 @@ export const getFlowContext = async (): Promise => { throw new Error("No runId associated with the current workflow execution"); } - const { createEntitiesAsDraft, dataSources, userAuthentication, webId } = - await getAiWorkflowParams({ - workflowId, - }); + const { + createEntitiesAsDraft, + dataSources, + flowTriggerEntityId, + userAuthentication, + webId, + } = await getAiWorkflowParams({ + workflowId, + }); // Query for the flow entity by workflowId (stored as a property on the entity) // This is necessary because the entity UUID may not match the workflow ID @@ -167,6 +176,7 @@ export const getFlowContext = async (): Promise => { dataSources, userAuthentication, flowEntityId, + flowTriggerEntityId, runId, webId, stepId, diff --git a/apps/hash-api/package.json b/apps/hash-api/package.json index a57d83baf59..db9d0cdd701 100644 --- a/apps/hash-api/package.json +++ b/apps/hash-api/package.json @@ -32,8 +32,6 @@ "@apollo/utils.keyvadapter": "4.0.1", "@as-integrations/express5": "1.1.2", "@aws-sdk/client-s3": "3.986.0", - "@aws-sdk/client-sesv2": "3.986.0", - "@aws-sdk/credential-provider-node": "3.972.84", "@aws-sdk/s3-request-presigner": "3.986.0", "@blockprotocol/core": "0.1.5", "@blockprotocol/graph": "workspace:*", @@ -86,16 +84,13 @@ "graphql-scalars": "2.0.1", "helmet": "4.6.0", "hot-shots": "8.5.2", - "html-to-text": "8.2.1", "http-proxy-middleware": "patch:http-proxy-middleware@npm%3A3.0.7#~/.yarn/patches/http-proxy-middleware-npm-3.0.7-89cd070ac6.patch", "http-terminator": "3.2.0", "immer": "10.2.0", - "js-yaml": "4.3.2", "keyv": "5.6.0", "long": "5.3.2", "mime-types": "2.1.35", "nanoid": "3.3.20", - "nodemailer": "10.1.7", "oembed-providers": "1.0.20250926", "openai": "6.6.0", "sanitize-html": "2.18.1", @@ -116,8 +111,6 @@ "@types/app-root-path": "3.1.0", "@types/cors": "2.8.19", "@types/dedent": "0.7.2", - "@types/html-to-text": "8.1.1", - "@types/js-yaml": "^4", "@types/mailchimp__mailchimp_marketing": "3.0.21", "@types/mime-types": "2.1.4", "@types/node": "catalog:", diff --git a/apps/hash-api/src/email/create-email-transporter.test.ts b/apps/hash-api/src/email/create-email-transporter.test.ts new file mode 100644 index 00000000000..18bf22a07dd --- /dev/null +++ b/apps/hash-api/src/email/create-email-transporter.test.ts @@ -0,0 +1,38 @@ +import { expect, it, vi } from "vitest"; + +import { + createEmailTransporter as createSendingEmailTransporter, + EmailSendError, +} from "@local/hash-backend-utils/email"; + +import { logger } from "../logger"; +import { createEmailTransporter } from "./create-email-transporter"; + +vi.mock("@local/hash-backend-utils/email", async (importOriginal) => ({ + ...(await importOriginal()), + createEmailTransporter: vi.fn(), +})); +vi.mock("../logger", () => ({ logger: { error: vi.fn(), info: vi.fn() } })); + +/* Invitations and mentions send an email as part of a request, which a failed send mustn't fail. */ +it("logs a failed send, with the provider's error, rather than rejecting", async () => { + const providerError = new Error("Email address is not verified."); + + vi.mocked(createSendingEmailTransporter).mockReturnValue({ + sendMail: () => + Promise.reject(new EmailSendError("rejected", providerError)), + }); + + await expect( + createEmailTransporter().sendMail({ + to: "ada@example.com", + subject: "You've been invited", + html: "

Hi

", + }), + ).resolves.toBeUndefined(); + + expect(logger.error).toHaveBeenCalledExactlyOnceWith("Error sending email", { + error: providerError, + outcome: "rejected", + }); +}); diff --git a/apps/hash-api/src/email/create-email-transporter.ts b/apps/hash-api/src/email/create-email-transporter.ts index 216b91bc192..4aae0c1f78c 100644 --- a/apps/hash-api/src/email/create-email-transporter.ts +++ b/apps/hash-api/src/email/create-email-transporter.ts @@ -1,10 +1,7 @@ -import path from "node:path"; - -import { getAwsRegion } from "@local/hash-backend-utils/aws-config"; import { - getRequiredEnv, - monorepoRootDir, -} from "@local/hash-backend-utils/environment"; + createEmailTransporter as createSendingEmailTransporter, + EmailSendError, +} from "@local/hash-backend-utils/email"; import { isDevEnv, @@ -13,59 +10,60 @@ import { isTestEnv, } from "../lib/env-config"; import { logger } from "../logger"; -import { AwsSesEmailTransporter, DummyEmailTransporter } from "./transporters"; -import { SmtpEmailTransporter } from "./transporters/smtp-email-transporter"; -import type { EmailTransporter } from "./transporters/types"; +import type { EmailTransporterSendMailOptions } from "@local/hash-backend-utils/email"; -const transporterType = process.env.HASH_EMAIL_TRANSPORTER; +/** + * Sends the API's own emails, such as invitations. A send that fails is logged rather than thrown, so that it doesn't + * fail the request it is part of. + */ +export type EmailTransporter = { + sendMail( + options: Pick, + ): Promise; +}; export const createEmailTransporter = (): EmailTransporter => { - if (transporterType === "dummy") { - if (!(isDevEnv || isTestEnv)) { - logger.error( - "HASH_EMAIL_TRANSPORTER is set to dummy, but application is running in production mode.", - ); - } - - return new DummyEmailTransporter({ - filePath: process.env.DUMMY_EMAIL_TRANSPORTER_FILE_PATH - ? path.resolve( - monorepoRootDir, - process.env.DUMMY_EMAIL_TRANSPORTER_FILE_PATH, - ) - : undefined, - }); + if ( + process.env.HASH_EMAIL_TRANSPORTER === "dummy" && + !(isDevEnv || isTestEnv) + ) { + logger.error( + "HASH_EMAIL_TRANSPORTER is set to dummy, but application is running in production mode.", + ); } - const subjectPrefix = isProdEnv - ? undefined - : isStagingEnv - ? "[STAGING SITE] " - : "[DEV SITE] "; - - if (transporterType === "aws") { - return new AwsSesEmailTransporter({ - from: `${getRequiredEnv( - "SYSTEM_EMAIL_SENDER_NAME", - )} <${getRequiredEnv("SYSTEM_EMAIL_ADDRESS")}>`, - region: getAwsRegion(), - subjectPrefix, - }); - } + const transporter = createSendingEmailTransporter({ + logger, + subjectPrefix: isProdEnv + ? undefined + : isStagingEnv + ? "[STAGING SITE] " + : "[DEV SITE] ", + dummyFilePath: process.env.DUMMY_EMAIL_TRANSPORTER_FILE_PATH, + }); - if (transporterType === "smtp") { - return new SmtpEmailTransporter({ - from: `${getRequiredEnv( - "SYSTEM_EMAIL_SENDER_NAME", - )} <${getRequiredEnv("SYSTEM_EMAIL_ADDRESS")}>`, - subjectPrefix, - }); + if (!transporter) { + return { + sendMail: (mail) => { + logger.info(`Tried to send mail to ${mail.to}`, { html: mail.html }); + }, + } as EmailTransporter; } return { - sendMail: (mail) => { - logger.info(`Tried to send mail to ${mail.to}`, { html: mail.html }); - }, - } as EmailTransporter; + sendMail: (mail) => + transporter.sendMail(mail).then( + () => undefined, + (error: unknown) => { + /* The provider's own error, as was logged before the transporters said what became of the email. */ + logger.error( + "Error sending email", + error instanceof EmailSendError + ? { error: error.cause, outcome: error.outcome } + : { error }, + ); + }, + ), + }; }; diff --git a/apps/hash-api/src/email/transporters/aws-ses-email-transporter.ts b/apps/hash-api/src/email/transporters/aws-ses-email-transporter.ts deleted file mode 100644 index b39d6f09229..00000000000 --- a/apps/hash-api/src/email/transporters/aws-ses-email-transporter.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { SendEmailCommand, SESv2Client } from "@aws-sdk/client-sesv2"; -import { defaultProvider } from "@aws-sdk/credential-provider-node"; -import { convert } from "html-to-text"; -import nodemailer from "nodemailer"; - -import { logger } from "../../logger"; - -import type { - EmailTransporter, - EmailTransporterSendMailOptions, -} from "./types"; -import type { SESSentMessageInfo, Transporter } from "nodemailer"; - -export interface AwsSesEmailTransporterConfig { - from: string; - region: string; - subjectPrefix?: string; -} - -export class AwsSesEmailTransporter implements EmailTransporter { - private nodemailerTransporter: Transporter; - private ses: SESv2Client; - - constructor(private config: AwsSesEmailTransporterConfig) { - this.ses = new SESv2Client({ - apiVersion: "2010-12-01", - region: config.region, - credentialDefaultProvider: defaultProvider, - }); - this.nodemailerTransporter = nodemailer.createTransport({ - SES: { sesClient: this.ses, SendEmailCommand }, - }); - } - - async sendMail({ to, subject, html }: EmailTransporterSendMailOptions) { - return this.nodemailerTransporter - .sendMail({ - from: this.config.from, - to, - subject: `${this.config.subjectPrefix ?? ""}${subject}`, - text: convert(html), - html, - }) - .then(() => undefined) - .catch((error) => { - logger.error("Error sending email", { error }); - }); - } -} diff --git a/apps/hash-api/src/email/transporters/index.ts b/apps/hash-api/src/email/transporters/index.ts deleted file mode 100644 index d908d4ad2ad..00000000000 --- a/apps/hash-api/src/email/transporters/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./aws-ses-email-transporter"; -export * from "./dummy-email-transporter"; -export * from "./types"; diff --git a/apps/hash-api/src/email/transporters/smtp-email-transporter.ts b/apps/hash-api/src/email/transporters/smtp-email-transporter.ts deleted file mode 100644 index 3a6b3b924ad..00000000000 --- a/apps/hash-api/src/email/transporters/smtp-email-transporter.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { convert } from "html-to-text"; -import nodemailer from "nodemailer"; - -import { getRequiredEnv } from "@local/hash-backend-utils/environment"; - -import { logger } from "../../logger"; - -import type { - EmailTransporter, - EmailTransporterSendMailOptions, -} from "./types"; -import type { SMTPSentMessageInfo, Transporter } from "nodemailer"; - -export interface SmtpEmailTransporterConfig { - from: string; - subjectPrefix?: string; -} - -export class SmtpEmailTransporter implements EmailTransporter { - private nodemailerTransporter: Transporter; - - constructor(private config: SmtpEmailTransporterConfig) { - const host = getRequiredEnv("SMTP_SERVER_HOST"); - const port = parseInt(getRequiredEnv("SMTP_SERVER_PORT"), 10); - const username = process.env.SMTP_SERVER_USERNAME; - const password = username - ? getRequiredEnv("SMTP_SERVER_PASSWORD") - : process.env.SMTP_SERVER_PASSWORD; - - this.nodemailerTransporter = nodemailer.createTransport({ - host, - port, - ...(username && password - ? { - auth: { - type: "login", - user: username, - pass: password, - }, - } - : {}), - secure: port === 465, - }); - } - - async sendMail({ to, subject, html }: EmailTransporterSendMailOptions) { - return this.nodemailerTransporter - .sendMail({ - from: this.config.from, - to, - subject: `${this.config.subjectPrefix ?? ""}${subject}`, - text: convert(html), - html, - }) - .then(() => undefined) - .catch((error) => { - logger.error("Error sending email", { error }); - }); - } -} diff --git a/apps/hash-api/src/email/transporters/types.ts b/apps/hash-api/src/email/transporters/types.ts deleted file mode 100644 index 5219bd36095..00000000000 --- a/apps/hash-api/src/email/transporters/types.ts +++ /dev/null @@ -1,9 +0,0 @@ -export interface EmailTransporterSendMailOptions { - to: string; - subject: string; - html: string; -} - -export interface EmailTransporter { - sendMail(options: EmailTransporterSendMailOptions): Promise; -} diff --git a/apps/hash-api/src/graph/context-types.ts b/apps/hash-api/src/graph/context-types.ts index 6d720af8675..0f2e9230c56 100644 --- a/apps/hash-api/src/graph/context-types.ts +++ b/apps/hash-api/src/graph/context-types.ts @@ -1,4 +1,4 @@ -import type { EmailTransporter } from "../email/transporters"; +import type { EmailTransporter } from "../email/create-email-transporter"; import type { ActorType, OriginProvenance } from "@blockprotocol/type-system"; import type { FileStorageProvider } from "@local/hash-backend-utils/file-storage"; import type { Logger } from "@local/hash-backend-utils/logger"; diff --git a/apps/hash-api/src/graphql/context.ts b/apps/hash-api/src/graphql/context.ts index 91944de1668..e5abf4f2691 100644 --- a/apps/hash-api/src/graphql/context.ts +++ b/apps/hash-api/src/graphql/context.ts @@ -1,4 +1,4 @@ -import type { EmailTransporter } from "../email/transporters"; +import type { EmailTransporter } from "../email/create-email-transporter"; import type { GraphApi } from "../graph/context-types"; import type { User } from "../graph/knowledge/system-types/user"; import type { ProvidedEntityEditionProvenance } from "@blockprotocol/type-system"; diff --git a/apps/hash-api/src/graphql/create-apollo-server.ts b/apps/hash-api/src/graphql/create-apollo-server.ts index a61e3787407..8de27dd5cb0 100644 --- a/apps/hash-api/src/graphql/create-apollo-server.ts +++ b/apps/hash-api/src/graphql/create-apollo-server.ts @@ -25,7 +25,7 @@ import { getActorIdFromRequest } from "../auth/get-actor-id"; import { isProdEnv } from "../lib/env-config"; import { resolvers } from "./resolvers"; -import type { EmailTransporter } from "../email/transporters"; +import type { EmailTransporter } from "../email/create-email-transporter"; import type { GraphApi } from "../graph/context-types"; import type { GraphQLContext } from "./context"; import type { FileStorageProvider } from "@local/hash-backend-utils/file-storage"; diff --git a/apps/hash-api/src/graphql/resolvers/knowledge/org/invite-user-to-org.ts b/apps/hash-api/src/graphql/resolvers/knowledge/org/invite-user-to-org.ts index 30d5fdfbb5f..1b47061d668 100644 --- a/apps/hash-api/src/graphql/resolvers/knowledge/org/invite-user-to-org.ts +++ b/apps/hash-api/src/graphql/resolvers/knowledge/org/invite-user-to-org.ts @@ -38,7 +38,7 @@ import * as Error from "../../../error"; import { graphQLContextToImpureGraphContext } from "../../util"; import { getPendingOrgInvitationsFromSubgraph } from "./shared"; -import type { EmailTransporter } from "../../../../email/transporters"; +import type { EmailTransporter } from "../../../../email/create-email-transporter"; import type { ResolverFn } from "../../../api-types.gen"; import type { LoggedInGraphQLContext } from "../../../context"; import type { MutationInviteUserToOrgArgs } from "@local/hash-isomorphic-utils/graphql/api-types.gen"; diff --git a/apps/hash-frontend/src/pages/@/[shortname]/flows/[flow-def-id]/edit.page/shared/step-display.test.ts b/apps/hash-frontend/src/pages/@/[shortname]/flows/[flow-def-id]/edit.page/shared/step-display.test.ts index f3afaa959fc..c053d648d62 100644 --- a/apps/hash-frontend/src/pages/@/[shortname]/flows/[flow-def-id]/edit.page/shared/step-display.test.ts +++ b/apps/hash-frontend/src/pages/@/[shortname]/flows/[flow-def-id]/edit.page/shared/step-display.test.ts @@ -34,7 +34,7 @@ describe("getListedActionGroups", () => { .flatMap(({ actions }) => actions) .filter(isUpcomingAction), ), - ).toEqual(["Ask a person", "Send email"]); + ).toEqual(["Ask a person"]); }); it("leaves For each out inside a for-each step, also from a search", () => { diff --git a/apps/hash-frontend/src/pages/@/[shortname]/flows/[flow-def-id]/edit.page/shared/step-display.ts b/apps/hash-frontend/src/pages/@/[shortname]/flows/[flow-def-id]/edit.page/shared/step-display.ts index a98a4c91b99..b1c8fc0f0d2 100644 --- a/apps/hash-frontend/src/pages/@/[shortname]/flows/[flow-def-id]/edit.page/shared/step-display.ts +++ b/apps/hash-frontend/src/pages/@/[shortname]/flows/[flow-def-id]/edit.page/shared/step-display.ts @@ -99,8 +99,8 @@ const forEachListing = { } as const satisfies ForEachListing; /** - * In the order each group lists them. Ask a person (FE-1987) and Send email (FE-1832) can be added once they have a - * definition. Wait (FE-2012) and the definitions kept from before the editor aren't listed. + * In the order each group lists them. Ask a person (FE-1987) can be added once it has a definition. Wait (FE-2012) and + * the definitions kept from before the editor aren't listed. */ const listedActions: ListedAction[] = [ { @@ -111,9 +111,9 @@ const listedActions: ListedAction[] = [ icon: "user", }, { - upcomingId: "sendEmail", + actionDefinitionId: "sendEmail", label: "Send email", - description: "Send an email to people", + description: "Send a plain-text email to one address", groupId: "messages", icon: "at", }, diff --git a/libs/@local/hash-backend-utils/package.json b/libs/@local/hash-backend-utils/package.json index a1a8e78e540..1f509ebf2f1 100644 --- a/libs/@local/hash-backend-utils/package.json +++ b/libs/@local/hash-backend-utils/package.json @@ -25,6 +25,7 @@ "dependencies": { "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/client-s3": "3.986.0", + "@aws-sdk/client-sesv2": "3.986.0", "@aws-sdk/credential-provider-node": "3.972.84", "@aws-sdk/s3-request-presigner": "3.986.0", "@blockprotocol/core": "0.1.5", @@ -62,11 +63,15 @@ "@temporalio/workflow": "1.20.2", "axios": "1.20.0", "cache-manager": "5.7.6", + "dedent": "1.7.0", "dotenv-flow": "3.3.0", "exponential-backoff": "3.1.3", "googleapis": "133.0.0", + "html-to-text": "8.2.1", + "js-yaml": "4.3.2", "logform": "2.7.0", "mime-types": "2.1.35", + "nodemailer": "10.1.7", "redis": "5.12.1", "undici": "6.29.1", "uuid": "14.0.0", @@ -79,7 +84,10 @@ "@local/flow-petri-net": "workspace:*", "@local/tsconfig": "workspace:*", "@tsconfig/bases": "catalog:", + "@types/dedent": "0.7.2", "@types/dotenv-flow": "3.3.3", + "@types/html-to-text": "8.1.1", + "@types/js-yaml": "^4", "@types/mime-types": "2.1.4", "@types/node": "catalog:", "@types/wait-on": "5.3.4", diff --git a/libs/@local/hash-backend-utils/src/email.ts b/libs/@local/hash-backend-utils/src/email.ts new file mode 100644 index 00000000000..f59fdad82ae --- /dev/null +++ b/libs/@local/hash-backend-utils/src/email.ts @@ -0,0 +1,90 @@ +import path from "node:path"; + +import { getAwsRegion } from "./aws-config.js"; +import { AwsSesEmailTransporter } from "./email/aws-ses-email-transporter.js"; +import { DummyEmailTransporter } from "./email/dummy-email-transporter.js"; +import { SmtpEmailTransporter } from "./email/smtp-email-transporter.js"; +import { getRequiredEnv, monorepoRootDir } from "./environment.js"; + +import type { + EmailTransporter, + SendTimeout, +} from "./email/shared/email-transporter.js"; +import type { Logger } from "./logger.js"; + +export { AwsSesEmailTransporter } from "./email/aws-ses-email-transporter.js"; +export type { + EmailSendFailureOutcome, + EmailTransporter, + EmailTransporterSendMailOptions, +} from "./email/shared/email-transporter.js"; +export { EmailSendError } from "./email/shared/email-transporter.js"; + +type CreateEmailTransporterParams = { + logger: Pick; + /** + * The sender of an email that doesn't name one. By default, `SYSTEM_EMAIL_SENDER_NAME `, both + * of which the `aws` and `smtp` transporters then need. + */ + from?: string; + subjectPrefix?: string; + /** + * Where the `dummy` transporter writes the emails it's given, relative to the monorepo root. It empties the file + * when it starts, so each service that creates a transporter needs a file of its own. + */ + dummyFilePath?: string; + /** Tries each send once and gives up on it after this long, for a caller that decides itself whether to retry. */ + singleAttempt?: SendTimeout; +}; + +/** + * Creates the transporter `HASH_EMAIL_TRANSPORTER` names: `aws` sends through SES with the AWS credentials of the + * environment, `smtp` through the server `SMTP_SERVER_HOST` and `SMTP_SERVER_PORT` name, and `dummy` sends nothing, + * and logs each email instead. + * + * @returns `null` if `HASH_EMAIL_TRANSPORTER` names none of them, so no email can be sent. + */ +export const createEmailTransporter = ({ + logger, + from, + subjectPrefix, + dummyFilePath, + singleAttempt, +}: CreateEmailTransporterParams): EmailTransporter | null => { + const transporterType = process.env.HASH_EMAIL_TRANSPORTER; + + if (transporterType === "dummy") { + return new DummyEmailTransporter({ + logger, + filePath: dummyFilePath + ? path.resolve(monorepoRootDir, dummyFilePath) + : undefined, + from, + }); + } + + const getFrom = () => + from ?? + `${getRequiredEnv("SYSTEM_EMAIL_SENDER_NAME")} <${getRequiredEnv( + "SYSTEM_EMAIL_ADDRESS", + )}>`; + + if (transporterType === "aws") { + return new AwsSesEmailTransporter({ + from: getFrom(), + region: getAwsRegion(), + subjectPrefix, + singleAttempt, + }); + } + + if (transporterType === "smtp") { + return new SmtpEmailTransporter({ + from: getFrom(), + subjectPrefix, + timeout: singleAttempt, + }); + } + + return null; +}; diff --git a/libs/@local/hash-backend-utils/src/email/aws-ses-email-transporter.test.ts b/libs/@local/hash-backend-utils/src/email/aws-ses-email-transporter.test.ts new file mode 100644 index 00000000000..4a7bedcc49a --- /dev/null +++ b/libs/@local/hash-backend-utils/src/email/aws-ses-email-transporter.test.ts @@ -0,0 +1,204 @@ +import { createServer } from "node:http"; + +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; + +import { AwsSesEmailTransporter } from "./aws-ses-email-transporter.js"; +import { EmailSendError } from "./shared/email-transporter.js"; + +import type { IncomingMessage, Server, ServerResponse } from "node:http"; +import type { AddressInfo } from "node:net"; + +type SesRequest = { + FromEmailAddress: string; + Destination: { ToAddresses: string[] }; + /** The email as sent, with its headers. */ + raw: string; +}; + +/** The requests the stand-in for SES received, and how it answers the next ones. */ +const requests: SesRequest[] = []; +let answer: (response: ServerResponse) => void; + +const answerWith = + (status: number, body: object, errorType?: string) => + (response: ServerResponse) => { + response.writeHead(status, { + "content-type": "application/json", + ...(errorType ? { "x-amzn-errortype": errorType } : {}), + }); + response.end(JSON.stringify(body)); + }; + +const readBody = async (request: IncomingMessage) => { + const chunks: Buffer[] = []; + + for await (const chunk of request) { + chunks.push(chunk as Buffer); + } + + return Buffer.concat(chunks).toString("utf-8"); +}; + +let server: Server; + +beforeAll(async () => { + server = createServer((request, response) => { + void readBody(request).then((body) => { + const sent = JSON.parse(body) as Omit & { + Content: { Raw: { Data: string } }; + }; + + requests.push({ + FromEmailAddress: sent.FromEmailAddress, + Destination: sent.Destination, + raw: Buffer.from(sent.Content.Raw.Data, "base64").toString("utf-8"), + }); + + answer(response); + }); + }); + + await new Promise((resolve) => { + server.listen(0, "127.0.0.1", resolve); + }); + + /* + * The AWS SDK reads these when a client is created. The stand-in checks no signature, so any credentials do. They're + * set as one object because code scanning fails on a literal assigned to a variable named "secret", `nosemgrep` or not. + */ + Object.assign(process.env, { + AWS_ENDPOINT_URL_SESV2: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, + AWS_ACCESS_KEY_ID: "test", + AWS_SECRET_ACCESS_KEY: "test", + }); +}); + +afterAll(() => { + server.closeAllConnections(); + server.close(); +}); + +beforeEach(() => { + requests.length = 0; +}); + +const singleAttempt = { connectionTimeoutMs: 1_000, responseTimeoutMs: 300 }; + +const createTransporter = ( + config: Partial[0]> = {}, +) => + new AwsSesEmailTransporter({ + from: "sender@example.com", + region: "us-east-1", + ...config, + }); + +const email = { + to: "ada@hash.ai", + subject: "Order shipped", + html: "

Hi Ada

", +}; + +/** What became of the email, as the transporter reports a send that failed. */ +const failedSendOutcome = async (transporter: AwsSesEmailTransporter) => { + const error: unknown = await transporter.sendMail(email).then( + () => undefined, + (thrown: unknown) => thrown, + ); + + expect(error).toBeInstanceOf(EmailSendError); + + return (error as EmailSendError).outcome; +}; + +describe("AwsSesEmailTransporter", () => { + it("returns the ID SES gives the email, and sends it from and to the addresses given", async () => { + answer = answerWith(200, { MessageId: "0100018f-abc-000000" }); + + await expect( + createTransporter({ subjectPrefix: "[STAGING SITE] " }).sendMail({ + ...email, + from: "flows@example.com", + replyTo: "grace@example.com", + text: "Hi Ada, in plain text", + }), + ).resolves.toEqual({ messageId: "0100018f-abc-000000" }); + + expect(requests).toHaveLength(1); + expect(requests[0]).toMatchObject({ + FromEmailAddress: "flows@example.com", + Destination: { ToAddresses: ["ada@hash.ai"] }, + }); + + const { raw } = requests[0]!; + + expect(raw).toMatch(/^From: flows@example\.com\r$/m); + expect(raw).toMatch(/^Reply-To: grace@example\.com\r$/m); + expect(raw).toMatch(/^Subject: \[STAGING SITE\] Order shipped\r$/m); + expect(raw).toContain("Hi Ada, in plain text"); + expect(raw).toContain("

Hi Ada

"); + }); + + it("sends from its own sender, with the HTML as text, when the email gives neither", async () => { + answer = answerWith(200, { MessageId: "id" }); + + await createTransporter().sendMail(email); + + const { raw } = requests[0]!; + + expect(raw).toMatch(/^From: sender@example\.com\r$/m); + expect(raw).not.toMatch(/^Reply-To:/m); + expect(raw).toContain("Hi Ada\r\n"); + }); + + it.each([ + [ + "rejected, for an email SES refuses", + answerWith( + 400, + { message: "Email address is not verified." }, + "MessageRejected", + ), + "rejected", + ], + [ + "unavailable, while SES is throttling", + answerWith( + 429, + { message: "Maximum sending rate exceeded." }, + "TooManyRequestsException", + ), + "unavailable", + ], + [ + "unknown, when SES fails while handling the email", + answerWith(500, { message: "Internal failure" }), + "unknown", + ], + ["unknown, when SES doesn't answer in time", () => {}, "unknown"], + ])("reports a failed send as %s", async (_, sesAnswer, outcome) => { + answer = sesAnswer; + + await expect( + failedSendOutcome(createTransporter({ singleAttempt })), + ).resolves.toBe(outcome); + + /* One request each: trying again could send the email twice. */ + expect(requests).toHaveLength(1); + }); + + it("reports a failed send as unavailable when SES can't be reached", async () => { + const endpoint = process.env.AWS_ENDPOINT_URL_SESV2; + + /* A port nothing listens on. */ + process.env.AWS_ENDPOINT_URL_SESV2 = "http://127.0.0.1:1"; + + try { + await expect( + failedSendOutcome(createTransporter({ singleAttempt })), + ).resolves.toBe("unavailable"); + } finally { + process.env.AWS_ENDPOINT_URL_SESV2 = endpoint; + } + }); +}); diff --git a/libs/@local/hash-backend-utils/src/email/aws-ses-email-transporter.ts b/libs/@local/hash-backend-utils/src/email/aws-ses-email-transporter.ts new file mode 100644 index 00000000000..118a20a25f4 --- /dev/null +++ b/libs/@local/hash-backend-utils/src/email/aws-ses-email-transporter.ts @@ -0,0 +1,106 @@ +import { + SendEmailCommand, + SESv2Client, + SESv2ServiceException, +} from "@aws-sdk/client-sesv2"; +import { defaultProvider } from "@aws-sdk/credential-provider-node"; +import { convert } from "html-to-text"; +import nodemailer from "nodemailer"; + +import { EmailSendError, neverConnected } from "./shared/email-transporter.js"; + +import type { + EmailSendFailureOutcome, + EmailTransporter, + EmailTransporterSendMailOptions, + SendTimeout, +} from "./shared/email-transporter.js"; +import type { SESSentMessageInfo, Transporter } from "nodemailer"; + +export type AwsSesEmailTransporterConfig = { + from: string; + region: string; + subjectPrefix?: string; + /** + * Each send is one request to SES, given up on after this long. By default, the AWS SDK tries a request up to three + * times with no timeout, which can send an email twice. + */ + singleAttempt?: SendTimeout; +}; + +/** + * SES answering that the request is at fault means it didn't accept the email. Anything else leaves that unknown, + * unless the request was never made. + */ +const getSesSendFailureOutcome = (error: unknown): EmailSendFailureOutcome => { + if (error instanceof SESv2ServiceException) { + if (error.$fault !== "client") { + return "unknown"; + } + + return error.$metadata.httpStatusCode === 429 ? "unavailable" : "rejected"; + } + + /* Credentials are resolved before a request is signed and sent. */ + if ( + neverConnected(error) || + (error instanceof Error && error.name === "CredentialsProviderError") + ) { + return "unavailable"; + } + + return "unknown"; +}; + +export class AwsSesEmailTransporter implements EmailTransporter { + private nodemailerTransporter: Transporter; + private ses: SESv2Client; + + constructor(private config: AwsSesEmailTransporterConfig) { + const { singleAttempt } = config; + + this.ses = new SESv2Client({ + apiVersion: "2010-12-01", + region: config.region, + credentialDefaultProvider: defaultProvider, + ...(singleAttempt + ? { + maxAttempts: 1, + requestHandler: { + connectionTimeout: singleAttempt.connectionTimeoutMs, + requestTimeout: singleAttempt.responseTimeoutMs, + throwOnRequestTimeout: true, + }, + } + : {}), + }); + this.nodemailerTransporter = nodemailer.createTransport({ + SES: { sesClient: this.ses, SendEmailCommand }, + }); + } + + async sendMail({ + to, + subject, + html, + text, + from, + replyTo, + }: EmailTransporterSendMailOptions) { + try { + const { response } = await this.nodemailerTransporter.sendMail({ + from: from ?? this.config.from, + to, + replyTo, + subject: `${this.config.subjectPrefix ?? ""}${subject}`, + text: text ?? convert(html), + html, + }); + + /* The ID SES gave the email. `messageId` is the Message-ID header nodemailer builds from it. */ + return { messageId: response }; + } catch (error) { + throw new EmailSendError(getSesSendFailureOutcome(error), error); + } + } +} diff --git a/apps/hash-api/src/email/transporters/dummy-email-transporter.ts b/libs/@local/hash-backend-utils/src/email/dummy-email-transporter.ts similarity index 71% rename from apps/hash-api/src/email/transporters/dummy-email-transporter.ts rename to libs/@local/hash-backend-utils/src/email/dummy-email-transporter.ts index 137c9308bfa..de459240807 100644 --- a/apps/hash-api/src/email/transporters/dummy-email-transporter.ts +++ b/libs/@local/hash-backend-utils/src/email/dummy-email-transporter.ts @@ -1,3 +1,4 @@ +import { randomUUID } from "node:crypto"; import fs from "node:fs/promises"; import path from "node:path"; @@ -5,17 +6,18 @@ import dedent from "dedent"; import { convert } from "html-to-text"; import { dump } from "js-yaml"; -import { logger } from "../../logger"; - +import type { Logger } from "../logger.js"; import type { EmailTransporter, EmailTransporterSendMailOptions, -} from "./types"; +} from "./shared/email-transporter.js"; interface EmailDump { date: string; + messageId: string; from: string; to: string; + replyTo?: string; subject: string; text?: string; html?: string; @@ -23,16 +25,17 @@ interface EmailDump { const yamlFileHeader = dedent` ## This file has been autogenerated by DummyEmailTransporter. - ## The contents are updated every time the API server sends an email. + ## The contents are updated every time the service that writes it sends an email. ## Most recent emails are shown at the top, like in an inbox. ## - ## Note that the file is emptied when the API server is restarted. + ## Note that the file is emptied when that service is restarted. `; -export interface DummyEmailTransporterConfig { +export type DummyEmailTransporterConfig = { + logger: Pick; filePath?: string; from?: string; -} +}; const defaultFrom = "dummy-email-transporter@hash.test"; @@ -43,31 +46,43 @@ export class DummyEmailTransporter implements EmailTransporter { */ private emailDumps: EmailDump[] = []; - constructor(private config: DummyEmailTransporterConfig = {}) { + constructor(private config: DummyEmailTransporterConfig) { void this.writeEmailsToFile(); } - async sendMail({ to, subject, html }: EmailTransporterSendMailOptions) { + async sendMail({ + to, + subject, + html, + text, + from, + replyTo, + }: EmailTransporterSendMailOptions) { const emailDump: EmailDump = { date: new Date().toString(), - from: this.config.from ?? defaultFrom, + messageId: `dummy-${randomUUID()}`, + from: from ?? this.config.from ?? defaultFrom, to, + ...(replyTo ? { replyTo } : {}), subject, - text: convert(html), + text: text ?? convert(html), html, }; - await this.logEmail(emailDump); + this.logEmail(emailDump); this.emailDumps.unshift(emailDump); await this.writeEmailsToFile(); + + return { messageId: emailDump.messageId }; } - private async logEmail(emailDump: EmailDump): Promise { + private logEmail(emailDump: EmailDump): void { const rowsToDisplay: string[] = [ `New email to ${emailDump.to}!`, `Subject: ${emailDump.subject}`, `From: ${emailDump.from}`, + ...(emailDump.replyTo ? [`Reply-To: ${emailDump.replyTo}`] : []), `Date: ${emailDump.date}`, `Text: ${emailDump.text}`, "", @@ -114,7 +129,7 @@ export class DummyEmailTransporter implements EmailTransporter { await fs.writeFile(this.config.filePath, yamlFileContents, "utf-8"); } catch (error) { - logger.error(error as string); + this.config.logger.error(error as string); } } } diff --git a/libs/@local/hash-backend-utils/src/email/shared/email-transporter.ts b/libs/@local/hash-backend-utils/src/email/shared/email-transporter.ts new file mode 100644 index 00000000000..e76eaf230dc --- /dev/null +++ b/libs/@local/hash-backend-utils/src/email/shared/email-transporter.ts @@ -0,0 +1,54 @@ +export type EmailTransporterSendMailOptions = { + to: string; + subject: string; + html: string; + /** The plain-text alternative to `html`. Converted from `html` if not given. */ + text?: string; + /** The sender, in place of the transporter's own. */ + from?: string; + replyTo?: string; +}; + +export type EmailTransporter = { + /** @throws {EmailSendError} if the email wasn't sent, or may not have been. */ + sendMail( + options: EmailTransporterSendMailOptions, + ): Promise<{ messageId: string }>; +}; + +/** + * What became of an email whose send failed: + * - `rejected`: it wasn't sent, and sending the same email again would fail the same way. + * - `unavailable`: it wasn't sent, and sending it again later may work, e.g. the provider is throttling. + * - `unknown`: the provider may have accepted it, e.g. the connection dropped after the request was written. Sending + * it again may send it twice. + */ +export type EmailSendFailureOutcome = "rejected" | "unavailable" | "unknown"; + +export class EmailSendError extends Error { + override name = "EmailSendError"; + + readonly outcome: EmailSendFailureOutcome; + + constructor(outcome: EmailSendFailureOutcome, cause: unknown) { + super(cause instanceof Error ? cause.message : String(cause), { cause }); + this.outcome = outcome; + } +} + +const neverConnectedCodes = new Set(["EAI_AGAIN", "ECONNREFUSED", "ENOTFOUND"]); + +/** Whether `error` says no connection to the provider was made. `originalCode` is the code nodemailer replaced. */ +export const neverConnected = (error: unknown) => + typeof error === "object" && + error !== null && + ["code", "originalCode"].some((key) => + neverConnectedCodes.has(String((error as Record)[key])), + ); + +/** How long a send may take, for a transporter that gives up on a send that takes longer. */ +export type SendTimeout = { + connectionTimeoutMs: number; + /** Counted from when the connection is made. */ + responseTimeoutMs: number; +}; diff --git a/libs/@local/hash-backend-utils/src/email/smtp-email-transporter.test.ts b/libs/@local/hash-backend-utils/src/email/smtp-email-transporter.test.ts new file mode 100644 index 00000000000..5b77e3079cd --- /dev/null +++ b/libs/@local/hash-backend-utils/src/email/smtp-email-transporter.test.ts @@ -0,0 +1,118 @@ +import { createServer } from "node:net"; + +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +import { EmailSendError } from "./shared/email-transporter.js"; +import { SmtpEmailTransporter } from "./smtp-email-transporter.js"; + +import type { AddressInfo, Server } from "node:net"; + +/** How the stand-in for an SMTP server treats the next email: what it answers to `RCPT TO`, and to the message. */ +let behavior: { + recipient: string; + /** `null` to close the connection once it has the message, without answering. */ + message: string | null; +}; + +let server: Server; + +beforeAll(async () => { + server = createServer((socket) => { + let receivingMessage = false; + + socket.write("220 localhost ESMTP\r\n"); + + socket.on("data", (data) => { + const text = data.toString("utf-8"); + + if (receivingMessage) { + if (text.endsWith("\r\n.\r\n")) { + receivingMessage = false; + + if (behavior.message === null) { + socket.destroy(); + } else { + socket.write(`${behavior.message}\r\n`); + } + } + } else if (/^EHLO/i.test(text)) { + socket.write("250 localhost\r\n"); + } else if (/^RCPT TO/i.test(text)) { + socket.write(`${behavior.recipient}\r\n`); + } else if (/^DATA/i.test(text)) { + receivingMessage = true; + socket.write("354 Go ahead\r\n"); + } else if (/^QUIT/i.test(text)) { + socket.end("221 Bye\r\n"); + } else { + socket.write("250 OK\r\n"); + } + }); + + socket.on("error", () => {}); + }); + + await new Promise((resolve) => { + server.listen(0, "127.0.0.1", resolve); + }); + + process.env.SMTP_SERVER_HOST = "127.0.0.1"; +}); + +afterAll(() => { + server.close(); +}); + +const email = { to: "ada@hash.ai", subject: "Hello", html: "

Hi

" }; + +const send = (port = (server.address() as AddressInfo).port) => { + process.env.SMTP_SERVER_PORT = String(port); + + return new SmtpEmailTransporter({ from: "sender@example.com" }).sendMail( + email, + ); +}; + +const failedSendOutcome = async (port?: number) => { + const error: unknown = await send(port).then( + () => undefined, + (thrown: unknown) => thrown, + ); + + expect(error).toBeInstanceOf(EmailSendError); + + return (error as EmailSendError).outcome; +}; + +describe("SmtpEmailTransporter", () => { + it("returns the Message-ID of an email the server accepts", async () => { + behavior = { recipient: "250 OK", message: "250 Queued" }; + + const { messageId } = await send(); + + expect(messageId).toMatch(/^<.+@example\.com>$/); + }); + + it("reports an email the server refuses as rejected", async () => { + behavior = { recipient: "550 No such user", message: "250 Queued" }; + + await expect(failedSendOutcome()).resolves.toBe("rejected"); + }); + + it("reports an email the server can't take for now as unavailable", async () => { + behavior = { recipient: "250 OK", message: "451 Try again later" }; + + await expect(failedSendOutcome()).resolves.toBe("unavailable"); + }); + + it("reports a server that can't be reached as unavailable", async () => { + /* A port nothing listens on. */ + await expect(failedSendOutcome(1)).resolves.toBe("unavailable"); + }); + + it("reports a connection that drops once the server has the message as unknown", async () => { + behavior = { recipient: "250 OK", message: null }; + + await expect(failedSendOutcome()).resolves.toBe("unknown"); + }); +}); diff --git a/libs/@local/hash-backend-utils/src/email/smtp-email-transporter.ts b/libs/@local/hash-backend-utils/src/email/smtp-email-transporter.ts new file mode 100644 index 00000000000..1e21a8465f4 --- /dev/null +++ b/libs/@local/hash-backend-utils/src/email/smtp-email-transporter.ts @@ -0,0 +1,108 @@ +import { convert } from "html-to-text"; +import nodemailer from "nodemailer"; + +import { getRequiredEnv } from "../environment.js"; +import { EmailSendError, neverConnected } from "./shared/email-transporter.js"; + +import type { + EmailSendFailureOutcome, + EmailTransporter, + EmailTransporterSendMailOptions, + SendTimeout, +} from "./shared/email-transporter.js"; +import type { SMTPSentMessageInfo, Transporter } from "nodemailer"; + +export type SmtpEmailTransporterConfig = { + from: string; + subjectPrefix?: string; + /** + * How long a send may take before it's given up on. By default, nodemailer waits up to 2 minutes to connect and 10 + * for the server to answer. + */ + timeout?: SendTimeout; +}; + +/** Codes nodemailer gives an email it didn't hand to the server: one it can't address, or can't sign in to send. */ +const rejectedCodes = new Set(["EAUTH", "EENVELOPE", "ENOAUTH"]); + +/** + * A server that answers with an error didn't accept the email: for good with a 5xx, for now with a 4xx. Without such + * an answer, the email wasn't sent if no connection was made or nodemailer refused it, and otherwise may have been. + */ +const getSmtpSendFailureOutcome = (error: unknown): EmailSendFailureOutcome => { + const { code, responseCode } = ( + typeof error === "object" && error !== null ? error : {} + ) as { code?: unknown; responseCode?: unknown }; + + if (typeof responseCode === "number" && responseCode >= 400) { + return responseCode >= 500 ? "rejected" : "unavailable"; + } + + if (neverConnected(error) || code === "EDNS") { + return "unavailable"; + } + + return typeof code === "string" && rejectedCodes.has(code) + ? "rejected" + : "unknown"; +}; + +export class SmtpEmailTransporter implements EmailTransporter { + private nodemailerTransporter: Transporter; + + constructor(private config: SmtpEmailTransporterConfig) { + const host = getRequiredEnv("SMTP_SERVER_HOST"); + const port = parseInt(getRequiredEnv("SMTP_SERVER_PORT"), 10); + const username = process.env.SMTP_SERVER_USERNAME; + const password = username + ? getRequiredEnv("SMTP_SERVER_PASSWORD") + : process.env.SMTP_SERVER_PASSWORD; + + this.nodemailerTransporter = nodemailer.createTransport({ + host, + port, + ...(username && password + ? { + auth: { + type: "login", + user: username, + pass: password, + }, + } + : {}), + secure: port === 465, + ...(config.timeout + ? { + connectionTimeout: config.timeout.connectionTimeoutMs, + greetingTimeout: config.timeout.connectionTimeoutMs, + socketTimeout: config.timeout.responseTimeoutMs, + } + : {}), + }); + } + + async sendMail({ + to, + subject, + html, + text, + from, + replyTo, + }: EmailTransporterSendMailOptions) { + try { + /* An SMTP server gives an email no ID of its own, so this is the Message-ID header nodemailer gave it. */ + const { messageId } = await this.nodemailerTransporter.sendMail({ + from: from ?? this.config.from, + to, + replyTo, + subject: `${this.config.subjectPrefix ?? ""}${subject}`, + text: text ?? convert(html), + html, + }); + + return { messageId }; + } catch (error) { + throw new EmailSendError(getSmtpSendFailureOutcome(error), error); + } + } +} diff --git a/libs/@local/hash-isomorphic-utils/src/flows/action-definitions.ts b/libs/@local/hash-isomorphic-utils/src/flows/action-definitions.ts index d1b0dd2d44c..01f4767ee85 100644 --- a/libs/@local/hash-isomorphic-utils/src/flows/action-definitions.ts +++ b/libs/@local/hash-isomorphic-utils/src/flows/action-definitions.ts @@ -1,4 +1,5 @@ import { checkAggregationInput } from "./aggregation.js"; +import { checkSendEmailStep } from "./email-address.js"; import { checkQueryInput } from "./entity-query.js"; import { checkCreateEntityStep, @@ -51,6 +52,7 @@ export type AiFlowActionDefinitionId = | "persistEntity" | "queryEntities" | "researchEntities" + | "sendEmail" | "takeFirst" | "updateEntity" | "webSearch" @@ -1280,6 +1282,59 @@ const aiFlowActionDefinitionsAsConst = { }, ], }, + sendEmail: { + actionDefinitionId: "sendEmail", + activitySettings: defaultActivitySettings, + name: "Send Email", + description: + "Send one plain-text email to one address. An email that may already have been sent is never sent again: the step fails instead.", + kind: "action", + inputs: [ + { + oneOfPayloadKinds: ["Text"], + name: "to", + description: "The recipient's email address: one address.", + required: true, + array: false, + size: "short", + }, + { + oneOfPayloadKinds: ["Text"], + name: "subject", + description: "The email's subject line, on one line.", + required: true, + array: false, + size: "short", + }, + { + oneOfPayloadKinds: ["Text"], + name: "body", + description: + "The email's body, in plain text with line breaks: HTML and Markdown are sent as written, not formatted.", + required: true, + array: false, + }, + { + oneOfPayloadKinds: ["Text"], + name: "replyTo", + description: + "The address replies go to. By default, the email address of the person who started the run.", + required: false, + array: false, + size: "short", + }, + ], + outputs: [ + { + payloadKind: "Text", + name: "messageId", + description: "The ID the email provider gave the email.", + array: false, + required: true, + }, + ], + check: checkSendEmailStep, + }, takeFirst: { actionDefinitionId: "takeFirst", activitySettings: defaultActivitySettings, diff --git a/libs/@local/hash-isomorphic-utils/src/flows/email-address.test.ts b/libs/@local/hash-isomorphic-utils/src/flows/email-address.test.ts new file mode 100644 index 00000000000..a359bf5b081 --- /dev/null +++ b/libs/@local/hash-isomorphic-utils/src/flows/email-address.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vitest"; + +import { validateEmailAddress } from "./email-address.js"; + +describe("validateEmailAddress", () => { + it.each(["ada@hash.ai", "Ada.Lovelace+flows@mail.example.co.uk"])( + "accepts %s", + (address) => { + expect(validateEmailAddress(address)).toBeUndefined(); + }, + ); + + /* Each would add a recipient or a header, or isn't an address a mail server delivers to. */ + it.each([ + ["a list", "ada@hash.ai, grace@example.com"], + ["a list without a space", "ada@hash.ai;grace@example.com"], + ["a display name", "Ada "], + ["an address in angle brackets", ""], + ["a line break", "ada@hash.ai\r\nBcc: grace@example.com"], + ["a space", "ada @hash.ai"], + ["two @ signs", "ada@hash.ai@example.com"], + ["no domain", "ada"], + ["a domain without a dot", "ada@localhost"], + ["nothing", ""], + [ + "an address longer than a mail server takes", + `${"a".repeat(250)}@hash.ai`, + ], + ])("rejects %s", (_, address) => { + expect(validateEmailAddress(address)).toEqual(expect.any(String)); + }); +}); diff --git a/libs/@local/hash-isomorphic-utils/src/flows/email-address.ts b/libs/@local/hash-isomorphic-utils/src/flows/email-address.ts new file mode 100644 index 00000000000..83ba52ae092 --- /dev/null +++ b/libs/@local/hash-isomorphic-utils/src/flows/email-address.ts @@ -0,0 +1,45 @@ +import type { ActionStepCheck } from "./types.js"; + +/** The characters of a name before the `@` that need no quoting, and dot-separated labels with a top-level domain. */ +const emailAddressPattern = + /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9-]+(\.[a-z0-9-]+)+$/i; + +/** The longest address a mail server accepts. */ +const maxEmailAddressLength = 254; + +/** + * Checks that a value is one bare email address, such as `ada@example.com`: not a list of them, and without a + * display name, angle brackets or spaces, so that a value can't add a recipient or a header to an email. + */ +export const validateEmailAddress = (address: string): string | undefined => + address.length <= maxEmailAddressLength && emailAddressPattern.test(address) + ? undefined + : `"${address}" isn't a single email address, such as ada@example.com.`; + +/** Checks the typed addresses of a Send email step when the flow is defined. A blank Reply-to counts as not given. */ +export const checkSendEmailStep: ActionStepCheck = ({ step, report }) => { + for (const inputName of ["to", "replyTo"] as const) { + const source = step.inputs[inputName]; + + /* An address of another shape is reported as an incompatible connection. */ + if ( + source?.kind !== "constant" || + source.payload.kind !== "Text" || + typeof source.payload.value !== "string" + ) { + continue; + } + + const address = source.payload.value.trim(); + + if (inputName === "replyTo" && !address) { + continue; + } + + const error = validateEmailAddress(address); + + if (error) { + report(inputName, error); + } + } +}; diff --git a/libs/@local/hash-isomorphic-utils/src/flows/validate-flow-definition.test.ts b/libs/@local/hash-isomorphic-utils/src/flows/validate-flow-definition.test.ts index 8efb45a0064..54548887543 100644 --- a/libs/@local/hash-isomorphic-utils/src/flows/validate-flow-definition.test.ts +++ b/libs/@local/hash-isomorphic-utils/src/flows/validate-flow-definition.test.ts @@ -1946,6 +1946,62 @@ describe("validateFlowDefinition", () => { }); }); + describe("addresses of sendEmail steps", () => { + const sendEmailDefinition = (inputs: { to: string; replyTo?: string }) => ({ + ...baseDefinition, + inputs: [], + steps: [ + { + kind: "action", + stepId: "send", + actionDefinitionId: "sendEmail", + description: "", + inputs: Object.fromEntries( + Object.entries({ + subject: "Hello", + body: "Hi Ada", + ...inputs, + }).map(([inputName, value]) => [ + inputName, + { kind: "constant", payload: { kind: "Text", value } }, + ]), + ), + }, + ], + }); + + it.each([ + { to: " ada@hash.ai " }, + { to: "ada@hash.ai", replyTo: "grace@example.com" }, + /* A Reply-to left blank is one that isn't given. */ + { to: "ada@hash.ai", replyTo: " " }, + ])("accepts $to with a Reply-to of $replyTo", (inputs) => { + expect(diagnosticsOf(sendEmailDefinition(inputs))).toEqual([]); + }); + + it("rejects a typed recipient or Reply-to that isn't one address, on its input", () => { + expect( + diagnosticsOf( + sendEmailDefinition({ + to: "ada@hash.ai, grace@example.com", + replyTo: "ada", + }), + ), + ).toEqual([ + { + severity: "error", + code: "invalidInput", + path: ["steps", 0, "inputs", "to"], + }, + { + severity: "error", + code: "invalidInput", + path: ["steps", 0, "inputs", "replyTo"], + }, + ]); + }); + }); + describe("counts of takeFirst steps", () => { const takeFirstDefinition = (count: number) => ({ ...baseDefinition, diff --git a/tests/hash-backend-integration/src/tests/email.test.ts b/tests/hash-backend-integration/src/tests/email.test.ts index 645d6987867..be7798d791b 100644 --- a/tests/hash-backend-integration/src/tests/email.test.ts +++ b/tests/hash-backend-integration/src/tests/email.test.ts @@ -1,8 +1,8 @@ import "./load-test-env"; import { it } from "vitest"; -import { AwsSesEmailTransporter } from "@apps/hash-api/src/email/transporters"; import { getAwsRegion } from "@local/hash-backend-utils/aws-config"; +import { AwsSesEmailTransporter } from "@local/hash-backend-utils/email"; import { getRequiredEnv } from "@local/hash-backend-utils/environment"; it("can send an email", async ({ skip }) => { diff --git a/yarn.lock b/yarn.lock index d2d3e781ff9..8bdd2c48f47 100644 --- a/yarn.lock +++ b/yarn.lock @@ -506,8 +506,6 @@ __metadata: "@apollo/utils.keyvadapter": "npm:4.0.1" "@as-integrations/express5": "npm:1.1.2" "@aws-sdk/client-s3": "npm:3.986.0" - "@aws-sdk/client-sesv2": "npm:3.986.0" - "@aws-sdk/credential-provider-node": "npm:3.972.84" "@aws-sdk/s3-request-presigner": "npm:3.986.0" "@blockprotocol/core": "npm:0.1.5" "@blockprotocol/graph": "workspace:*" @@ -555,8 +553,6 @@ __metadata: "@types/app-root-path": "npm:3.1.0" "@types/cors": "npm:2.8.19" "@types/dedent": "npm:0.7.2" - "@types/html-to-text": "npm:8.1.1" - "@types/js-yaml": "npm:^4" "@types/mailchimp__mailchimp_marketing": "npm:3.0.21" "@types/mime-types": "npm:2.1.4" "@types/node": "catalog:" @@ -580,16 +576,13 @@ __metadata: graphql-scalars: "npm:2.0.1" helmet: "npm:4.6.0" hot-shots: "npm:8.5.2" - html-to-text: "npm:8.2.1" http-proxy-middleware: "patch:http-proxy-middleware@npm%3A3.0.7#~/.yarn/patches/http-proxy-middleware-npm-3.0.7-89cd070ac6.patch" http-terminator: "npm:3.2.0" immer: "npm:10.2.0" - js-yaml: "npm:4.3.2" keyv: "npm:5.6.0" long: "npm:5.3.2" mime-types: "npm:2.1.35" nanoid: "npm:3.3.20" - nodemailer: "npm:10.1.7" oembed-providers: "npm:1.0.20250926" openai: "npm:6.6.0" rimraf: "npm:6.1.4" @@ -9190,6 +9183,7 @@ __metadata: dependencies: "@aws-crypto/sha256-js": "npm:5.2.0" "@aws-sdk/client-s3": "npm:3.986.0" + "@aws-sdk/client-sesv2": "npm:3.986.0" "@aws-sdk/credential-provider-node": "npm:3.972.84" "@aws-sdk/s3-request-presigner": "npm:3.986.0" "@blockprotocol/core": "npm:0.1.5" @@ -9229,19 +9223,26 @@ __metadata: "@temporalio/worker": "npm:1.20.2" "@temporalio/workflow": "npm:1.20.2" "@tsconfig/bases": "catalog:" + "@types/dedent": "npm:0.7.2" "@types/dotenv-flow": "npm:3.3.3" + "@types/html-to-text": "npm:8.1.1" + "@types/js-yaml": "npm:^4" "@types/mime-types": "npm:2.1.4" "@types/node": "catalog:" "@types/wait-on": "npm:5.3.4" "@vitest/coverage-istanbul": "catalog:" axios: "npm:1.20.0" cache-manager: "npm:5.7.6" + dedent: "npm:1.7.0" dotenv-flow: "npm:3.3.0" eslint: "npm:9.39.4" exponential-backoff: "npm:3.1.3" googleapis: "npm:133.0.0" + html-to-text: "npm:8.2.1" + js-yaml: "npm:4.3.2" logform: "npm:2.7.0" mime-types: "npm:2.1.35" + nodemailer: "npm:10.1.7" redis: "npm:5.12.1" rimraf: "npm:6.1.4" typescript: "catalog:"