Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(email): report skipped invites and retain hosted sign-in failures

Rishabh Bothra4068cd12ae6f
diff --git a/apps/web/__tests__/unit/auth-options.test.ts b/apps/web/__tests__/unit/auth-options.test.ts
index 3b2ccf11c..ce8ff722a 100644
--- a/apps/web/__tests__/unit/auth-options.test.ts
+++ b/apps/web/__tests__/unit/auth-options.test.ts
@@ -11,7 +11,8 @@ import type { SQL } from "drizzle-orm";
import { MySqlDialect } from "drizzle-orm/mysql-core";
import type { Account, NextAuthOptions } from "next-auth";
import type { Adapter } from "next-auth/adapters";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { EmailConfig } from "next-auth/providers/email";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
type AuthUser = {
id: string;
@@ -34,6 +35,7 @@ const mocks = vi.hoisted(() => ({
options: { getSsoIdentity: () => ValidatedSsoIdentity | null },
) => Adapter
>(() => ({})),
+ isCap: undefined as string | undefined,
}));
const env = vi.hoisted(() => ({
@@ -57,6 +59,11 @@ const env = vi.hoisted(() => ({
vi.mock("@cap/env", () => ({
serverEnv: () => env,
+ buildEnv: {
+ get NEXT_PUBLIC_IS_CAP() {
+ return mocks.isCap;
+ },
+ },
}));
vi.mock("@cap/database", () => ({
@@ -122,6 +129,7 @@ function providerIds(options: NextAuthOptions) {
describe("authOptions", () => {
beforeEach(() => {
+ mocks.isCap = undefined;
env.APPLE_CLIENT_ID = "so.cap.auth";
env.APPLE_CLIENT_SECRET = "apple-secret";
env.WORKOS_CLIENT_ID = "workos-client";
@@ -160,6 +168,36 @@ describe("authOptions", () => {
}));
});
+ afterEach(() => vi.unstubAllEnvs());
+
+ it.each([false, true])(
+ "only logs undelivered codes for self-hosts (Cap Cloud: %j)",
+ async (isCap) => {
+ mocks.isCap = isCap ? "true" : undefined;
+ vi.stubEnv("NODE_ENV", "production");
+ const log = vi.spyOn(console, "log").mockImplementation(() => {});
+ const provider = authOptions().providers.find(
+ (provider) => provider.id === "email",
+ ) as EmailConfig;
+ const options = provider.options as EmailConfig;
+ const result = options.sendVerificationRequest({
+ identifier: "[email protected]",
+ token: "123456",
+ url: "http://localhost/verify",
+ expires: new Date(),
+ provider,
+ theme: {},
+ });
+ if (isCap) {
+ await expect(result).rejects.toThrow("RESEND_API_KEY");
+ expect(log).not.toHaveBeenCalled();
+ } else {
+ await result;
+ expect(log).toHaveBeenCalledWith("πŸ”’ Code: 123456");
+ }
+ },
+ );
+
it("enables Apple when both OAuth credentials are configured", () => {
const options = authOptions();
const providers = options.providers.map((provider) => provider.id);
diff --git a/apps/web/__tests__/unit/email-config.test.ts b/apps/web/__tests__/unit/email-config.test.ts
index 56aeb1479..562f28be8 100644
--- a/apps/web/__tests__/unit/email-config.test.ts
+++ b/apps/web/__tests__/unit/email-config.test.ts
@@ -49,14 +49,6 @@ describe("email config", () => {
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 });
diff --git a/apps/web/__tests__/unit/mobile-email-session.test.ts b/apps/web/__tests__/unit/mobile-email-session.test.ts
index 8d103a4fb..c6855f180 100644
--- a/apps/web/__tests__/unit/mobile-email-session.test.ts
+++ b/apps/web/__tests__/unit/mobile-email-session.test.ts
@@ -5,6 +5,7 @@ import { MySqlDialect } from "drizzle-orm/mysql-core";
import type { Context, Layer as EffectLayer } from "effect";
import {
afterAll,
+ afterEach,
beforeAll,
beforeEach,
describe,
@@ -18,6 +19,10 @@ type TokenRow = { identifier: string; token: string; expires: Date };
const mocks = vi.hoisted(() => ({
isRateLimited: vi.fn<(ruleId: string, opts?: unknown) => Promise<boolean>>(),
sendEmail: vi.fn<(input: { react: { code: string } }) => Promise<void>>(),
+ emailStatus: { configured: true } as
+ | { configured: true }
+ | { configured: false; reason: string },
+ isCap: undefined as string | undefined,
tokenRow: null as TokenRow | null,
selectBarrier: null as null | { size: number; waiting: (() => void)[] },
apiKeys: [] as string[],
@@ -30,7 +35,22 @@ vi.mock("@/lib/rate-limit", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/rate-limit")>()),
isRateLimited: mocks.isRateLimited,
}));
-vi.mock("@cap/database/emails/config", () => ({ sendEmail: mocks.sendEmail }));
+vi.mock("@cap/database/emails/config", () => ({
+ sendEmail: mocks.sendEmail,
+ getEmailDeliveryStatus: () => mocks.emailStatus,
+}));
+vi.mock("@cap/env", async (importOriginal) => {
+ const original = await importOriginal<typeof import("@cap/env")>();
+ return {
+ ...original,
+ buildEnv: {
+ ...original.buildEnv,
+ get NEXT_PUBLIC_IS_CAP() {
+ return mocks.isCap;
+ },
+ },
+ };
+});
vi.mock("@cap/database/emails/otp-email", () => ({
OTPEmail: (props: { code: string; email: string }) => props,
}));
@@ -206,12 +226,15 @@ describe("mobile email sessions", () => {
beforeEach(() => {
mocks.isRateLimited.mockReset().mockResolvedValue(false);
mocks.sendEmail.mockReset().mockResolvedValue(undefined);
+ mocks.emailStatus = { configured: true };
+ mocks.isCap = undefined;
mocks.tokenRow = null;
mocks.selectBarrier = null;
mocks.apiKeys = [];
});
afterAll(() => mocks.dispose());
+ afterEach(() => vi.unstubAllEnvs());
const post = (path: string, body: unknown) =>
POST(
@@ -232,6 +255,42 @@ describe("mobile email sessions", () => {
const wrongCode = (code: string) => (code === "123456" ? "654321" : "123456");
+ it("logs a usable code for a self-host with email disabled", async () => {
+ mocks.emailStatus = {
+ configured: false,
+ reason: "Email is not configured",
+ };
+ vi.stubEnv("NODE_ENV", "production");
+ const log = vi.spyOn(console, "log").mockImplementation(() => {});
+ const response = await post("request", { email: "[email protected]" });
+ expect(response.status).toBe(200);
+ expect(mocks.sendEmail).not.toHaveBeenCalled();
+ const codeLine = log.mock.calls.find(([line]) =>
+ /^Code: \d{6}$/.test(line),
+ );
+ expect(codeLine).toBeDefined();
+ const code = String(codeLine?.[0]).slice("Code: ".length);
+ expect(
+ (await post("verify", { email: "[email protected]", code })).status,
+ ).toBe(200);
+ });
+
+ it("fails on Cap Cloud without printing a code when email is disabled", async () => {
+ mocks.emailStatus = {
+ configured: false,
+ reason: "Email is not configured",
+ };
+ mocks.isCap = "true";
+ vi.stubEnv("NODE_ENV", "production");
+ const log = vi.spyOn(console, "log").mockImplementation(() => {});
+ const response = await post("request", { email: "[email protected]" });
+ expect(response.status).toBe(500);
+ expect(mocks.sendEmail).not.toHaveBeenCalled();
+ expect(
+ log.mock.calls.some(([line]) => /^Code: \d{6}$/.test(String(line))),
+ ).toBe(false);
+ });
+
it("sends a code and signs in with it", async () => {
const code = await requestCode(" [email protected] ");
diff --git a/apps/web/__tests__/unit/organization-invite-delivery.test.ts b/apps/web/__tests__/unit/organization-invite-delivery.test.ts
new file mode 100644
index 000000000..0df89c938
--- /dev/null
+++ b/apps/web/__tests__/unit/organization-invite-delivery.test.ts
@@ -0,0 +1,101 @@
+import { Organisation } from "@cap/web-domain";
+import type { SQL } from "drizzle-orm";
+import { MySqlDialect } from "drizzle-orm/mysql-core";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { sendOrganizationInvites } from "@/actions/organization/send-invites";
+
+const mocks = vi.hoisted(() => ({
+ sendEmail: vi.fn(),
+ insert: vi.fn(),
+ delete: vi.fn(),
+ sequence: 0,
+}));
+
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: async () => ({ id: "user-1" }),
+}));
+vi.mock("@cap/database/emails/config", () => ({ sendEmail: mocks.sendEmail }));
+vi.mock("@cap/database/emails/organization-invite", () => ({
+ OrganizationInvite: (props: unknown) => props,
+}));
+vi.mock("@cap/database/helpers", () => ({
+ nanoId: () => `invite-${++mocks.sequence}`,
+}));
+vi.mock("@cap/env", () => ({
+ serverEnv: () => ({ WEB_URL: "https://cap.example" }),
+}));
+vi.mock("@/lib/organization-provisioning", () => ({
+ provisionOrganizationInvitee: vi.fn(),
+}));
+vi.mock("@/actions/organization/authorization", () => ({
+ requireOrganizationSettingsManager: vi.fn(),
+}));
+vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
+vi.mock("@cap/database", () => {
+ const tx = {
+ select: () => ({
+ from: () => ({
+ where: async () => [],
+ innerJoin: () => ({ where: async () => [] }),
+ }),
+ }),
+ insert: () => ({ values: mocks.insert }),
+ };
+ return {
+ db: () => ({
+ select: () => ({
+ from: () => ({ where: async () => [{ id: "org-1", name: "Team" }] }),
+ }),
+ transaction: async (callback: (value: typeof tx) => Promise<unknown>) =>
+ callback(tx),
+ delete: () => ({ where: mocks.delete }),
+ }),
+ };
+});
+
+describe("organization invite delivery", () => {
+ beforeEach(() => {
+ mocks.sequence = 0;
+ mocks.sendEmail.mockReset();
+ });
+
+ it("preserves skipped invite records and reports them separately", async () => {
+ mocks.sendEmail.mockResolvedValue({
+ error: { name: "email_not_configured" },
+ });
+ const result = await sendOrganizationInvites(
+ Organisation.OrganisationId.make("org-1"),
+ );
+ expect(result).toMatchObject({
+ failedEmails: [],
+ skippedEmails: ["[email protected]"],
+ });
+ expect(mocks.insert).toHaveBeenCalledWith([
+ expect.objectContaining({
+ id: "invite-1",
+ invitedEmail: "[email protected]",
+ }),
+ ]);
+ expect(mocks.delete).not.toHaveBeenCalled();
+ });
+
+ it("cleans up only failed deliveries in a mixed batch", async () => {
+ mocks.sendEmail
+ .mockResolvedValueOnce({ error: { name: "email_not_configured" } })
+ .mockResolvedValueOnce({ error: { name: "validation_error" } })
+ .mockResolvedValueOnce({ data: { id: "sent" }, error: null });
+ const result = await sendOrganizationInvites(
+ Organisation.OrganisationId.make("org-1"),
+ );
+ expect(result).toMatchObject({
+ failedEmails: ["[email protected]"],
+ skippedEmails: ["[email protected]"],
+ });
+ const condition = mocks.delete.mock.calls[0]?.[0] as SQL;
+ expect(new MySqlDialect().sqlToQuery(condition).params).toEqual([
+ "invite-2",
+ ]);
+ });
+});
diff --git a/apps/web/actions/organization/send-invites.ts b/apps/web/actions/organization/send-invites.ts
index 94c25f97e..9032647b8 100644
--- a/apps/web/actions/organization/send-invites.ts
+++ b/apps/web/actions/organization/send-invites.ts
@@ -88,7 +88,11 @@ export async function sendOrganizationInvites(
const validEmails = validInvites.map((invite) => invite.email);
if (validEmails.length === 0) {
- return { success: true, failedEmails: [] as string[] };
+ return {
+ success: true,
+ failedEmails: [] as string[],
+ skippedEmails: [] as string[],
+ };
}
if (options.sendEmailNotifications === false) {
@@ -108,7 +112,7 @@ export async function sendOrganizationInvites(
revalidatePath("/dashboard/settings/organization");
- return { success: true, failedEmails };
+ return { success: true, failedEmails, skippedEmails: [] as string[] };
}
const inviteRecords = await db().transaction(async (tx) => {
@@ -191,6 +195,15 @@ export async function sendOrganizationInvites(
return Boolean(error && error.name !== "email_not_configured");
});
const failedEmails = failedInvites.map((r) => r.email);
+ const skippedEmails = inviteRecords
+ .filter((_, i) => {
+ const result = emailResults[i];
+ return (
+ result?.status === "fulfilled" &&
+ result.value?.error?.name === "email_not_configured"
+ );
+ })
+ .map((record) => record.email);
if (failedInvites.length > 0) {
try {
@@ -216,5 +229,5 @@ export async function sendOrganizationInvites(
revalidatePath("/dashboard/settings/organization");
- return { success: true, failedEmails };
+ return { success: true, failedEmails, skippedEmails };
}
diff --git a/apps/web/app/(org)/dashboard/settings/organization/components/InviteDialog.tsx b/apps/web/app/(org)/dashboard/settings/organization/components/InviteDialog.tsx
index c7e95947a..a66e862c7 100644
--- a/apps/web/app/(org)/dashboard/settings/organization/components/InviteDialog.tsx
+++ b/apps/web/app/(org)/dashboard/settings/organization/components/InviteDialog.tsx
@@ -114,13 +114,18 @@ export const InviteDialog = ({ isOpen, setIsOpen }: InviteDialogProps) => {
);
},
onSuccess: (result) => {
+ if (result.skippedEmails.length > 0) {
+ toast.warning(
+ `Invites created but not emailed because email is not configured. Share the invite links with: ${result.skippedEmails.join(", ")}`,
+ );
+ }
if (result.failedEmails.length > 0) {
toast.warning(
sendEmailNotifications
? `Invites sent, but delivery failed for: ${result.failedEmails.join(", ")}`
: `Users added, but provisioning failed for: ${result.failedEmails.join(", ")}`,
);
- } else {
+ } else if (result.skippedEmails.length === 0) {
toast.success(
sendEmailNotifications
? "Invites sent successfully"
diff --git a/apps/web/app/(org)/verify-otp/form.tsx b/apps/web/app/(org)/verify-otp/form.tsx
index 8a9da4296..e782d504a 100644
--- a/apps/web/app/(org)/verify-otp/form.tsx
+++ b/apps/web/app/(org)/verify-otp/form.tsx
@@ -135,7 +135,11 @@ export function VerifyOTPForm({
}
},
onSuccess: () => {
- toast.success("A new code has been sent to your email!");
+ toast.success(
+ emailDeliveryConfigured
+ ? "A new code has been sent to your email!"
+ : "A new code was printed to the server logs",
+ );
setCode(["", "", "", "", "", ""]);
inputRefs.current[0]?.focus();
setLastResendTime(Date.now());
diff --git a/apps/web/app/api/mobile/[...route]/route.ts b/apps/web/app/api/mobile/[...route]/route.ts
index 868ee16a8..a82816b39 100644
--- a/apps/web/app/api/mobile/[...route]/route.ts
+++ b/apps/web/app/api/mobile/[...route]/route.ts
@@ -7,7 +7,7 @@ import { OTPEmail } from "@cap/database/emails/otp-email";
import { nanoId } from "@cap/database/helpers";
import * as Db from "@cap/database/schema";
import { getNewVideoPublic } from "@cap/database/video-sharing-default";
-import { serverEnv } from "@cap/env";
+import { buildEnv, serverEnv } from "@cap/env";
import { userIsPro } from "@cap/utils";
import {
Database,
@@ -160,6 +160,9 @@ const hashEmailCode = (code: string) =>
const sendMobileEmailCode = async (email: string, code: string) => {
const emailStatus = getEmailDeliveryStatus();
if (!emailStatus.configured) {
+ if (process.env.NODE_ENV === "production" && buildEnv.NEXT_PUBLIC_IS_CAP) {
+ throw new Error(emailStatus.reason);
+ }
console.log("");
console.log("Cap mobile verification code (email delivery disabled)");
console.log(emailStatus.reason);
diff --git a/packages/database/auth/auth-options.ts b/packages/database/auth/auth-options.ts
index 2eca18ad3..119d6338d 100644
--- a/packages/database/auth/auth-options.ts
+++ b/packages/database/auth/auth-options.ts
@@ -1,5 +1,5 @@
import crypto from "node:crypto";
-import { serverEnv } from "@cap/env";
+import { buildEnv, serverEnv } from "@cap/env";
import { User } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import type { NextAuthOptions } from "next-auth";
@@ -261,6 +261,12 @@ export const authOptions = (ssoContext?: SsoAuthContext): NextAuthOptions => {
async sendVerificationRequest({ identifier, token }) {
const emailStatus = getEmailDeliveryStatus();
if (!emailStatus.configured) {
+ if (
+ process.env.NODE_ENV === "production" &&
+ buildEnv.NEXT_PUBLIC_IS_CAP
+ ) {
+ throw new Error(emailStatus.reason);
+ }
console.log("\n");
console.log(
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",