Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(email): never send from auth@undefined, fall back to logged codes and surface send failures
07rjainc951eeaffda1
diff --git a/apps/web/__tests__/unit/email-config.test.ts b/apps/web/__tests__/unit/email-config.test.tsnew file mode 100644index 000000000..56aeb1479--- /dev/null+++ b/apps/web/__tests__/unit/email-config.test.ts@@ -0,0 +1,96 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ env: {} as Record<string, string | undefined>,+ build: {} as Record<string, string | undefined>,+ send: vi.fn(),+}));++vi.mock("@cap/env", () => ({+ serverEnv: () => mocks.env,+ buildEnv: mocks.build,+}));++vi.mock("resend", () => ({+ Resend: class {+ emails = { send: mocks.send };+ },+}));++import { getEmailDeliveryStatus, sendEmail } from "@cap/database/emails/config";++const message = {+ email: "[email protected]",+ subject: "Hello",+ react: null as unknown as Parameters<typeof sendEmail>[0]["react"],+};++describe("email config", () => {+ beforeEach(() => {+ mocks.send.mockReset();+ for (const key of Object.keys(mocks.env)) delete mocks.env[key];+ for (const key of Object.keys(mocks.build)) delete mocks.build[key];+ });++ it("reports missing RESEND_API_KEY", () => {+ const status = getEmailDeliveryStatus();+ expect(status.configured).toBe(false);+ expect(status.configured ? "" : status.reason).toContain(+ "Email (Resend) is not configured",+ );+ });++ it("treats a missing RESEND_FROM_DOMAIN as not configured on self-hosted builds", async () => {+ mocks.env.RESEND_API_KEY = "re_test";+ expect(getEmailDeliveryStatus().configured).toBe(false);++ const result = await sendEmail(message);+ expect(mocks.send).not.toHaveBeenCalled();+ expect(result?.error?.name).toBe("email_not_configured");+ });++ it("never sends from auth@undefined", async () => {+ mocks.env.RESEND_API_KEY = "re_test";+ await sendEmail(message);+ for (const call of mocks.send.mock.calls) {+ expect(call[0].from).not.toContain("undefined");+ }+ });++ it("sends an explicit sender without a default from-domain", async () => {+ mocks.env.RESEND_API_KEY = "re_test";+ mocks.send.mockResolvedValue({ data: { id: "email_2" }, error: null });++ const result = await sendEmail({+ ...message,+ fromOverride: "Cap Support <[email protected]>",+ });++ expect(mocks.send.mock.calls[0]?.[0].from).toBe(+ "Cap Support <[email protected]>",+ );+ expect(result).toEqual({ data: { id: "email_2" }, error: null });+ });++ it("sends from the configured domain and returns the provider id", async () => {+ mocks.env.RESEND_API_KEY = "re_test";+ mocks.env.RESEND_FROM_DOMAIN = "example.com";+ mocks.send.mockResolvedValue({ data: { id: "email_1" }, error: null });++ const result = await sendEmail(message);+ expect(mocks.send.mock.calls[0]?.[0].from).toBe("[email protected]");+ expect(result).toEqual({ data: { id: "email_1" }, error: null });+ });++ it("surfaces provider rejections instead of claiming success", async () => {+ mocks.env.RESEND_API_KEY = "re_test";+ mocks.env.RESEND_FROM_DOMAIN = "example.com";+ mocks.send.mockResolvedValue({+ data: null,+ error: { name: "validation_error", message: "domain not verified" },+ });++ const result = await sendEmail(message);+ expect(result?.error?.message).toBe("domain not verified");+ });+});diff --git a/apps/web/actions/organization/send-invites.ts b/apps/web/actions/organization/send-invites.tsindex ad3642d4e..94c25f97e 100644--- a/apps/web/actions/organization/send-invites.ts+++ b/apps/web/actions/organization/send-invites.ts@@ -184,9 +184,12 @@ export async function sendOrganizationInvites(}),);- const failedInvites = inviteRecords.filter(- (_, i) => emailResults[i]?.status === "rejected",- );+ const failedInvites = inviteRecords.filter((_, i) => {+ const result = emailResults[i];+ if (!result || result.status === "rejected") return true;+ const error = result.value?.error;+ return Boolean(error && error.name !== "email_not_configured");+ });const failedEmails = failedInvites.map((r) => r.email);if (failedInvites.length > 0) {diff --git a/apps/web/app/(org)/verify-otp/form.tsx b/apps/web/app/(org)/verify-otp/form.tsxindex ca8a88d9b..8a9da4296 100644--- a/apps/web/app/(org)/verify-otp/form.tsx+++ b/apps/web/app/(org)/verify-otp/form.tsx@@ -16,10 +16,12 @@ export function VerifyOTPForm({email,next,lastSent,+ emailDeliveryConfigured = true,}: {email: string;next?: string;lastSent?: string;+ emailDeliveryConfigured?: boolean;}) {const [code, setCode] = useState(["", "", "", "", "", ""]);const [lastResendTime, setLastResendTime] = useState<number | null>(@@ -171,9 +173,17 @@ export function VerifyOTPForm({<h1 className="text-xl font-semibold text-gray-12">Enter verification code</h1>- <p className="text-sm text-gray-10">- We sent a 6-digit code to {normalizedEmail}- </p>+ {emailDeliveryConfigured ? (+ <p className="text-sm text-gray-10">+ We sent a 6-digit code to {normalizedEmail}+ </p>+ ) : (+ <p className="text-sm text-gray-10">+ Email (Resend) is not configured on this server. The 6-digit code+ for {normalizedEmail} was printed to the server logs. Ask your+ administrator, or set RESEND_API_KEY and RESEND_FROM_DOMAIN.+ </p>+ )}</div><div className="flex flex-1 gap-2 justify-between mb-5">diff --git a/apps/web/app/(org)/verify-otp/page.tsx b/apps/web/app/(org)/verify-otp/page.tsxindex 37abfc474..9c30b0d1e 100644--- a/apps/web/app/(org)/verify-otp/page.tsx+++ b/apps/web/app/(org)/verify-otp/page.tsx@@ -1,4 +1,5 @@import { getCurrentUser } from "@cap/database/auth/session";+import { isEmailDeliveryConfigured } from "@cap/database/emails/config";import { serverEnv } from "@cap/env";import { redirect } from "next/navigation";import { Suspense } from "react";@@ -30,6 +31,7 @@ export default async function VerifyOTPPage(props: {email={searchParams.email?.toLowerCase() ?? ""}next={searchParams.next}lastSent={searchParams.lastSent}+ emailDeliveryConfigured={isEmailDeliveryConfigured()}/></Suspense></div>diff --git a/apps/web/app/api/mobile/[...route]/route.ts b/apps/web/app/api/mobile/[...route]/route.tsindex 6c0320d5f..474a65b9b 100644--- a/apps/web/app/api/mobile/[...route]/route.ts+++ b/apps/web/app/api/mobile/[...route]/route.ts@@ -2,7 +2,7 @@ import crypto from "node:crypto";import { authOptions } from "@cap/database/auth/auth-options";import { isEmailAllowedForSignup } from "@cap/database/auth/domain-utils";import { hashPassword } from "@cap/database/crypto";-import { sendEmail } from "@cap/database/emails/config";+import { getEmailDeliveryStatus, sendEmail } from "@cap/database/emails/config";import { OTPEmail } from "@cap/database/emails/otp-email";import { nanoId } from "@cap/database/helpers";import * as Db from "@cap/database/schema";@@ -154,12 +154,11 @@ const hashEmailCode = (code: string) =>.digest("hex");const sendMobileEmailCode = async (email: string, code: string) => {- if (!serverEnv().RESEND_API_KEY) {- if (process.env.NODE_ENV === "production") {- throw new Error("RESEND_API_KEY is required to send mobile email codes");- }+ const emailStatus = getEmailDeliveryStatus();+ if (!emailStatus.configured) {console.log("");- console.log("Cap mobile verification code");+ console.log("Cap mobile verification code (email delivery disabled)");+ console.log(emailStatus.reason);console.log(`Email: ${email}`);console.log(`Code: ${code}`);console.log("Expires in: 10 minutes");@@ -167,11 +166,16 @@ const sendMobileEmailCode = async (email: string, code: string) => {return;}- await sendEmail({+ const delivery = await sendEmail({email,subject: "Your Cap Verification Code",react: OTPEmail({ code, email }),});+ if (delivery?.error) {+ throw new Error(+ `Failed to send verification email: ${delivery.error.message}`,+ );+ }};const getMobileRedirectUrl = (redirectUri: string) => {diff --git a/apps/web/app/api/v1/[...route]/route.ts b/apps/web/app/api/v1/[...route]/route.tsindex 5e889e3c4..0cfb4b550 100644--- a/apps/web/app/api/v1/[...route]/route.ts+++ b/apps/web/app/api/v1/[...route]/route.ts@@ -4912,8 +4912,15 @@ const AgentManagementHandlersLive = HttpApiBuilder.group(}),idempotencyKey: providerIdempotencyKey,});- if (delivery?.error)+ if (delivery?.error) {+ if (delivery.error.name === "email_not_configured") {+ return {+ ...invitation,+ emailDelivery: "not_configured" as const,+ };+ }throw new Error(delivery.error.message);+ }return {...invitation,emailDelivery: "accepted" as const,diff --git a/apps/web/content/docs/self-hosting.mdx b/apps/web/content/docs/self-hosting.mdxindex 45219a81b..29d07467c 100644--- a/apps/web/content/docs/self-hosting.mdx+++ b/apps/web/content/docs/self-hosting.mdx@@ -26,7 +26,7 @@ That's it! Cap will be available at `http://localhost:3000`.The default `docker-compose.yml` includes placeholder secrets for quick local testing. **If you're deploying to a public server or production environment**, you must change these values. See the [Production Checklist](#production-checklist) below.</Warning>-Login links will appear in the logs since email isn't configured:+Login codes will appear in the logs until email is configured, and the verify screen says "Email (Resend) is not configured":```bashdocker compose logs cap-web```@@ -97,7 +97,7 @@ For Coolify users, use `docker-compose.coolify.yml` which includes environment v## Email Configuration-By default, login links are printed to the server logs. To send emails:+Email is optional. Without it, login codes are printed to the cap-web logs, the verify screen shows "Email (Resend) is not configured", and invite or notification emails are skipped (invite links still work). Cap only sends email when **both** variables below are set; if Resend rejects a message, the error is logged and the sign-in fails instead of claiming a code was sent. To send emails:1. Create an account at [Resend](https://resend.com)2. Add these environment variables:@@ -105,6 +105,7 @@ By default, login links are printed to the server logs. To send emails:RESEND_API_KEY=re_xxxxxRESEND_FROM_DOMAIN=yourdomain.com```+3. Verify the domain in Resend. Login emails are sent from `auth@RESEND_FROM_DOMAIN`.## Optional Featuresdiff --git a/apps/web/lib/account-deletion-request.ts b/apps/web/lib/account-deletion-request.tsindex 8a21645b7..3468a0263 100644--- a/apps/web/lib/account-deletion-request.ts+++ b/apps/web/lib/account-deletion-request.ts@@ -164,7 +164,7 @@ export const createAccountDeletionRequest = async ({fromOverride: ACCOUNT_DELETION_EMAIL_FROM,idempotencyKey: `account-deletion-${request.id}`,})- .then(() => true)+ .then((delivery) => !delivery?.error).catch(() => false);return {@@ -264,7 +264,7 @@ export const createMobileContentReport = async ({fromOverride: ACCOUNT_DELETION_EMAIL_FROM,idempotencyKey: `mobile-content-report-${request.id}`,})- .then(() => true)+ .then((delivery) => !delivery?.error).catch(() => false);return {diff --git a/packages/database/auth/auth-options.ts b/packages/database/auth/auth-options.tsindex 8d9c00f72..f97c5bd78 100644--- a/packages/database/auth/auth-options.ts+++ b/packages/database/auth/auth-options.ts@@ -11,7 +11,7 @@ import EmailProvider from "next-auth/providers/email";import GoogleProvider from "next-auth/providers/google";import type { Provider } from "next-auth/providers/index";import WorkOSProvider from "next-auth/providers/workos";-import { sendEmail } from "../emails/config.ts";+import { getEmailDeliveryStatus, sendEmail } from "../emails/config.ts";import { db } from "../index.ts";import { users } from "../schema.ts";import {@@ -191,12 +191,14 @@ export const authOptions = (ssoContext?: SsoAuthContext): NextAuthOptions => {return crypto.randomInt(100000, 1000000).toString();},async sendVerificationRequest({ identifier, token }) {- if (!serverEnv().RESEND_API_KEY) {+ const emailStatus = getEmailDeliveryStatus();+ if (!emailStatus.configured) {console.log("\n");console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",);- console.log("🔐 VERIFICATION CODE (Development Mode)");+ console.log("🔐 VERIFICATION CODE (email delivery disabled)");+ console.log(`ℹ️ ${emailStatus.reason}`);console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",);@@ -212,11 +214,16 @@ export const authOptions = (ssoContext?: SsoAuthContext): NextAuthOptions => {} else {const { OTPEmail } = await import("../emails/otp-email");const email = OTPEmail({ code: token, email: identifier });- await sendEmail({+ const delivery = await sendEmail({email: identifier,subject: `Your Cap Verification Code`,react: email,});+ if (delivery?.error) {+ throw new Error(+ `Failed to send verification email: ${delivery.error.message}`,+ );+ }}},}),diff --git a/packages/database/emails/config.ts b/packages/database/emails/config.tsindex a5145c0d7..87ce2ea35 100644--- a/packages/database/emails/config.ts+++ b/packages/database/emails/config.ts@@ -5,6 +5,46 @@ import { Resend } from "resend";export const resend = () =>serverEnv().RESEND_API_KEY ? new Resend(serverEnv().RESEND_API_KEY) : null;+export const EMAIL_NOT_CONFIGURED_MESSAGE = "Email (Resend) is not configured";++export type EmailDeliveryStatus =+ | { configured: true }+ | { configured: false; reason: string };++export function getEmailDeliveryStatus(): EmailDeliveryStatus {+ const env = serverEnv();+ if (!env.RESEND_API_KEY) {+ return {+ configured: false,+ reason: `${EMAIL_NOT_CONFIGURED_MESSAGE}: RESEND_API_KEY is not set`,+ };+ }+ if (!buildEnv.NEXT_PUBLIC_IS_CAP && !env.RESEND_FROM_DOMAIN?.trim()) {+ return {+ configured: false,+ reason: `${EMAIL_NOT_CONFIGURED_MESSAGE}: RESEND_FROM_DOMAIN is not set`,+ };+ }+ return { configured: true };+}++export const isEmailDeliveryConfigured = () =>+ getEmailDeliveryStatus().configured;++let warnedEmailNotConfigured = false;++function warnEmailNotConfigured(reason: string) {+ if (warnedEmailNotConfigured) return;+ warnedEmailNotConfigured = true;+ console.warn(+ `[email] ${reason}. Emails will not be sent; login codes are printed to the server log instead.`,+ );+}++export type SendEmailResult =+ | { data: { id: string } | null; error: null }+ | { data: null; error: { name: string; message: string } };+export const sendEmail = async ({email,subject,@@ -33,22 +73,38 @@ export const sendEmail = async ({content: Buffer | string;contentType?: string;}[];-}) => {+}): Promise<SendEmailResult | undefined> => {+ const env = serverEnv();const r = resend();- if (!r) {- return Promise.resolve();+ if (!env.RESEND_API_KEY || !r) {+ const reason = `${EMAIL_NOT_CONFIGURED_MESSAGE}: RESEND_API_KEY is not set`;+ warnEmailNotConfigured(reason);+ return {+ data: null,+ error: { name: "email_not_configured", message: reason },+ };}if (marketing && !buildEnv.NEXT_PUBLIC_IS_CAP) return;- let from: string;-- if (fromOverride) from = fromOverride;- else if (marketing) from = "Richie from Cap <[email protected]>";- else if (buildEnv.NEXT_PUBLIC_IS_CAP)- from = "Cap Auth <[email protected]>";- else from = `auth@${serverEnv().RESEND_FROM_DOMAIN}`;+ const from = fromOverride+ ? fromOverride+ : marketing+ ? "Richie from Cap <[email protected]>"+ : buildEnv.NEXT_PUBLIC_IS_CAP+ ? "Cap Auth <[email protected]>"+ : env.RESEND_FROM_DOMAIN?.trim()+ ? `auth@${env.RESEND_FROM_DOMAIN.trim()}`+ : undefined;+ if (!from?.includes("@")) {+ const reason = `${EMAIL_NOT_CONFIGURED_MESSAGE}: RESEND_FROM_DOMAIN is not set`;+ warnEmailNotConfigured(reason);+ return {+ data: null,+ error: { name: "email_not_configured", message: reason },+ };+ }- return r.emails.send(+ const result = await r.emails.send({from,to: test ? "[email protected]" : email,@@ -61,4 +117,17 @@ export const sendEmail = async ({},idempotencyKey ? { idempotencyKey } : undefined,);++ if (result.error) {+ console.error(+ `[email] Resend rejected email "${subject}" from ${from}:`,+ result.error.message,+ );+ return {+ data: null,+ error: { name: result.error.name, message: result.error.message },+ };+ }++ return { data: result.data, error: null };};diff --git a/packages/web-domain/src/Agent.ts b/packages/web-domain/src/Agent.tsindex b09795d80..9a4c1f817 100644--- a/packages/web-domain/src/Agent.ts+++ b/packages/web-domain/src/Agent.ts@@ -695,7 +695,7 @@ export const AgentInvite = Schema.Struct({export const AgentOrganizationInviteResponse = Schema.Struct({invite: AgentInvite,inviteUrl: Schema.String,- emailDelivery: Schema.Literal("not_requested", "accepted"),+ emailDelivery: Schema.Literal("not_requested", "accepted", "not_configured"),requestId: Schema.String,});