Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: return viewer invitation validation feedback

Richie McIlroyc5f957a09cbf
diff --git a/apps/web/__tests__/unit/sharing-dialog-viewer-invites.test.ts b/apps/web/__tests__/unit/sharing-dialog-viewer-invites.test.ts
new file mode 100644
index 000000000..ac5483500
--- /dev/null
+++ b/apps/web/__tests__/unit/sharing-dialog-viewer-invites.test.ts
@@ -0,0 +1,240 @@
+// @vitest-environment jsdom
+
+import { Video } from "@cap/web-domain";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { inviteVideoViewer } from "@/actions/videos/viewer-invites";
+import { SharingDialog } from "@/app/(org)/dashboard/caps/components/SharingDialog";
+
+const mocks = vi.hoisted(() => ({
+ invite: vi.fn<typeof inviteVideoViewer>(),
+ grants: vi.fn(),
+ refresh: vi.fn(),
+ toast: { error: vi.fn(), success: vi.fn(), info: vi.fn(), warning: vi.fn() },
+}));
+
+vi.mock("@/actions/caps/share", () => ({ shareCap: vi.fn() }));
+vi.mock("@/actions/videos/password", () => ({
+ setVideoPassword: vi.fn(),
+ removeVideoPassword: vi.fn(),
+}));
+vi.mock("@/actions/videos/viewer-invites", () => ({
+ getVideoViewerGrants: mocks.grants,
+ inviteVideoViewer: mocks.invite,
+ revokeVideoViewer: vi.fn(),
+}));
+vi.mock("@/app/(org)/dashboard/Contexts", () => ({
+ useDashboardContext: () => undefined,
+}));
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ refresh: mocks.refresh }),
+}));
+vi.mock("sonner", () => ({ toast: mocks.toast }));
+vi.mock("@/utils/public-env", () => ({
+ usePublicEnv: () => ({ webUrl: "https://cap.example" }),
+}));
+vi.mock("@cap/utils", async () => await import("@cap/utils/helpers"));
+vi.mock("@cap/ui", async () => ({
+ ...(await import("../../../../packages/ui/src/components/Button")),
+ ...(await import("../../../../packages/ui/src/components/Dialog")),
+ ...(await import("../../../../packages/ui/src/components/Switch")),
+ ...(await import("../../../../packages/ui/src/components/input/Input")),
+}));
+
+let root: Root;
+let container: HTMLDivElement;
+let queryClient: QueryClient;
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ mocks.invite.mockReset();
+ mocks.grants.mockResolvedValue([]);
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ container.remove();
+ queryClient.clear();
+ vi.unstubAllGlobals();
+});
+
+async function render() {
+ await act(async () => {
+ root.render(
+ createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ createElement(SharingDialog, {
+ isOpen: true,
+ onClose: vi.fn(),
+ capId: Video.VideoId.make("video-id"),
+ capName: "Test video",
+ sharedSpaces: [],
+ onSharingUpdated: vi.fn(),
+ isPublic: false,
+ }),
+ ),
+ );
+ });
+ await flushUpdates();
+ expect(mocks.grants).toHaveBeenCalledOnce();
+}
+
+async function flushUpdates() {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+}
+
+function emailInput() {
+ const input = document.querySelector<HTMLInputElement>(
+ "input[placeholder='[email protected]']",
+ );
+ if (!input) throw new Error("Missing viewer email input");
+ return input;
+}
+
+function inviteButton() {
+ const button = Array.from(document.querySelectorAll("button")).find(
+ (element) => element.textContent === "Invite",
+ );
+ if (!button) throw new Error("Missing Invite button");
+ return button;
+}
+
+async function enterEmail(email: string) {
+ const setter = Object.getOwnPropertyDescriptor(
+ HTMLInputElement.prototype,
+ "value",
+ )?.set;
+ if (!setter) throw new Error("Missing input setter");
+ await act(async () => {
+ setter.call(emailInput(), email);
+ emailInput().dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+
+async function submit() {
+ await act(async () => inviteButton().click());
+ await flushUpdates();
+}
+
+function expectNoSuccessEffects() {
+ expect(mocks.grants).toHaveBeenCalledOnce();
+ expect(mocks.refresh).not.toHaveBeenCalled();
+ expect(mocks.toast.success).not.toHaveBeenCalled();
+ expect(mocks.toast.info).not.toHaveBeenCalled();
+ expect(mocks.toast.warning).not.toHaveBeenCalled();
+}
+
+describe("sharing dialog viewer invitations", () => {
+ it("preserves invalid input on repeated submits and allows correction", async () => {
+ mocks.invite.mockResolvedValue({
+ success: false,
+ error: "Enter a valid email address",
+ });
+ await render();
+ await enterEmail("invalid");
+ for (let attempt = 1; attempt <= 2; attempt++) {
+ await submit();
+ expect(mocks.invite).toHaveBeenCalledTimes(attempt);
+ expect(mocks.invite).toHaveBeenLastCalledWith("video-id", "invalid");
+ expect(mocks.toast.error).toHaveBeenLastCalledWith(
+ "Enter a valid email address",
+ );
+ expect(emailInput().value).toBe("invalid");
+ expect(inviteButton().disabled).toBe(false);
+ expectNoSuccessEffects();
+ }
+
+ mocks.invite.mockResolvedValue({
+ success: true,
+ alreadyAdded: false,
+ emailSent: true,
+ });
+ await enterEmail("[email protected]");
+ await submit();
+ expect(mocks.invite).toHaveBeenLastCalledWith(
+ "video-id",
+ );
+ expect(emailInput().value).toBe("");
+ expect(mocks.grants).toHaveBeenCalledTimes(2);
+ expect(mocks.refresh).toHaveBeenCalledOnce();
+ expect(mocks.toast.success).toHaveBeenCalledWith("Viewer invited");
+ });
+
+ it("blocks repeat clicks and edits while an invite is pending", async () => {
+ let finish: (
+ result: Awaited<ReturnType<typeof inviteVideoViewer>>,
+ ) => void = () => {
+ throw new Error("Invite has not started");
+ };
+ mocks.invite.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ await render();
+ await enterEmail("[email protected]");
+ const button = inviteButton();
+ await submit();
+ expect(button.disabled).toBe(true);
+ expect(emailInput().disabled).toBe(true);
+ await act(async () => button.click());
+ expect(mocks.invite).toHaveBeenCalledOnce();
+ await act(async () =>
+ finish({ success: true, alreadyAdded: false, emailSent: true }),
+ );
+ await flushUpdates();
+ expect(emailInput().disabled).toBe(false);
+ expect(emailInput().value).toBe("");
+ expect(mocks.toast.success).toHaveBeenCalledOnce();
+ });
+
+ it.each([
+ {
+ result: { success: true, alreadyAdded: true, emailSent: false },
+ toast: "info",
+ message: "This viewer already has access",
+ },
+ {
+ result: { success: true, alreadyAdded: false, emailSent: false },
+ toast: "warning",
+ message:
+ "Access added, but the invitation email was not sent. Copy the link to share it.",
+ },
+ ] as const)(
+ "preserves $toast feedback after granting access",
+ async ({ result, toast, message }) => {
+ mocks.invite.mockResolvedValue(result);
+ await render();
+ await enterEmail("[email protected]");
+ await submit();
+ expect(emailInput().value).toBe("");
+ expect(mocks.grants).toHaveBeenCalledTimes(2);
+ expect(mocks.refresh).toHaveBeenCalledOnce();
+ expect(mocks.toast[toast]).toHaveBeenCalledWith(message);
+ expect(mocks.toast.error).not.toHaveBeenCalled();
+ },
+ );
+
+ it("retains input and error feedback after an unexpected action failure", async () => {
+ mocks.invite.mockRejectedValue(new Error("Unable to invite viewer"));
+ await render();
+ await enterEmail("[email protected]");
+ await submit();
+ expect(emailInput().value).toBe("[email protected]");
+ expect(mocks.toast.error).toHaveBeenCalledWith("Unable to invite viewer");
+ expectNoSuccessEffects();
+ });
+});
diff --git a/apps/web/__tests__/unit/video-viewer-invites.test.ts b/apps/web/__tests__/unit/video-viewer-invites.test.ts
index 3719694de..b4680a91b 100644
--- a/apps/web/__tests__/unit/video-viewer-invites.test.ts
+++ b/apps/web/__tests__/unit/video-viewer-invites.test.ts
@@ -13,6 +13,7 @@ const fixtures = vi.hoisted(() => ({
video: { id: "video-1", ownerId: "owner-1", name: "Demo" },
grants: [] as string[],
revokedEmails: [] as string[],
+ selected: vi.fn(),
inserted: vi.fn(),
updated: vi.fn(),
}));
@@ -32,6 +33,7 @@ vi.mock("@cap/database", () => ({
return {
select: () => ({
from: (table: unknown) => {
+ fixtures.selected(table);
selectedTable = table;
return {
where: () => ({
@@ -103,14 +105,65 @@ describe("recording viewer invitations", () => {
});
});
- it("rejects a non-owner before writing a grant or sending email", async () => {
- fixtures.user.mockResolvedValue({ id: "other-1" });
+ it.each(["[email protected]", "invalid"])(
+ "rejects a non-owner before validating %s",
+ async (email) => {
+ fixtures.user.mockResolvedValue({ id: "other-1" });
- await expect(
- inviteVideoViewer(VIDEO_ID, "[email protected]"),
- ).rejects.toThrow("Unauthorized");
+ await expect(inviteVideoViewer(VIDEO_ID, email)).rejects.toThrow(
+ "Unauthorized",
+ );
+ expect(fixtures.inserted).not.toHaveBeenCalled();
+ expect(fixtures.sendEmail).not.toHaveBeenCalled();
+ },
+ );
+
+ it("rejects an unauthenticated caller before validation or database access", async () => {
+ fixtures.user.mockResolvedValue(null);
+
+ await expect(inviteVideoViewer(VIDEO_ID, "invalid")).rejects.toThrow(
+ "Unauthorized",
+ );
+ expect(fixtures.selected).not.toHaveBeenCalled();
expect(fixtures.inserted).not.toHaveBeenCalled();
expect(fixtures.sendEmail).not.toHaveBeenCalled();
+ expect(fixtures.revalidatePath).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ "",
+ " ",
+ "invalid",
+ "viewer@example",
+ "viewer@@example.com",
+ "viewer\[email protected]",
+ `${"a".repeat(243)}@example.com`,
+ ])(
+ "returns validation feedback for %j without looking up or changing grants",
+ async (email) => {
+ await expect(inviteVideoViewer(VIDEO_ID, email)).resolves.toEqual({
+ success: false,
+ error: "Enter a valid email address",
+ });
+ expect(fixtures.selected).toHaveBeenCalledExactlyOnceWith(schema.videos);
+ expect(fixtures.inserted).not.toHaveBeenCalled();
+ expect(fixtures.updated).not.toHaveBeenCalled();
+ expect(fixtures.sendEmail).not.toHaveBeenCalled();
+ expect(fixtures.revalidatePath).not.toHaveBeenCalled();
+ },
+ );
+
+ it("still accepts 254 characters after trimming and lowercasing", async () => {
+ const email = `${"A".repeat(242)}@Example.com`;
+ const result = await inviteVideoViewer(VIDEO_ID, ` ${email} `);
+
+ expect(result.success).toBe(true);
+ expect(fixtures.inserted).toHaveBeenCalledWith(
+ expect.objectContaining({ email: email.toLowerCase() }),
+ );
+ expect(fixtures.sendEmail).toHaveBeenCalledOnce();
});
it("grants access to the normalized email and sends the recording link", async () => {
@@ -137,7 +190,7 @@ describe("recording viewer invitations", () => {
const result = await inviteVideoViewer(VIDEO_ID, "[email protected]");
- expect(result.emailSent).toBe(false);
+ expect(result).toMatchObject({ success: true, emailSent: false });
expect(fixtures.inserted).toHaveBeenCalledOnce();
});
@@ -146,7 +199,11 @@ describe("recording viewer invitations", () => {
const result = await inviteVideoViewer(VIDEO_ID, "[email protected]");
- expect(result.alreadyAdded).toBe(true);
+ expect(result).toEqual({
+ success: true,
+ alreadyAdded: true,
+ emailSent: false,
+ });
expect(fixtures.inserted).not.toHaveBeenCalled();
expect(fixtures.sendEmail).not.toHaveBeenCalled();
});
@@ -157,11 +214,49 @@ describe("recording viewer invitations", () => {
const result = await inviteVideoViewer(VIDEO_ID, "[email protected]");
- expect(result.alreadyAdded).toBe(false);
+ expect(result).toMatchObject({
+ success: true,
+ alreadyAdded: false,
+ emailSent: true,
+ });
expect(fixtures.inserted).toHaveBeenCalledOnce();
expect(fixtures.sendEmail).toHaveBeenCalledOnce();
});
+ it("keeps unexpected grant failures as errors", async () => {
+ fixtures.inserted.mockRejectedValueOnce(new Error("Database unavailable"));
+
+ await expect(
+ inviteVideoViewer(VIDEO_ID, "[email protected]"),
+ ).rejects.toThrow("Database unavailable");
+ expect(fixtures.sendEmail).not.toHaveBeenCalled();
+ expect(fixtures.revalidatePath).not.toHaveBeenCalled();
+ });
+
+ it("keeps granted access when email delivery throws", async () => {
+ fixtures.sendEmail.mockRejectedValueOnce(new Error("Delivery unavailable"));
+ const log = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ await expect(
+ inviteVideoViewer(VIDEO_ID, "[email protected]"),
+ ).resolves.toEqual({
+ success: true,
+ alreadyAdded: false,
+ emailSent: false,
+ });
+ expect(fixtures.inserted).toHaveBeenCalledOnce();
+ expect(fixtures.revalidatePath).toHaveBeenCalledWith(`/s/${VIDEO_ID}`);
+ expect(log).toHaveBeenCalledOnce();
+ });
+
+ it("preserves invalid-address rejection when revoking", async () => {
+ await expect(revokeVideoViewer(VIDEO_ID, "invalid")).rejects.toThrow(
+ "Enter a valid email address",
+ );
+ expect(fixtures.updated).not.toHaveBeenCalled();
+ expect(fixtures.revalidatePath).not.toHaveBeenCalled();
+ });
+
it("keeps the invited viewer list and removal owner-only", async () => {
fixtures.grants = ["[email protected]"];
fixtures.user.mockResolvedValue({ id: "other-1" });
diff --git a/apps/web/actions/videos/viewer-invites.ts b/apps/web/actions/videos/viewer-invites.ts
index ffa895abd..cc66adc0f 100644
--- a/apps/web/actions/videos/viewer-invites.ts
+++ b/apps/web/actions/videos/viewer-invites.ts
@@ -30,7 +30,7 @@ async function getOwnedVideo(videoId: Video.VideoId) {
function normalizeEmail(email: string) {
const normalized = email.trim().toLowerCase();
if (normalized.length > 254 || !EMAIL_PATTERN.test(normalized)) {
- throw new Error("Enter a valid email address");
+ return null;
}
return normalized;
}
@@ -52,6 +52,9 @@ export async function getVideoViewerGrants(videoId: Video.VideoId) {
export async function inviteVideoViewer(videoId: Video.VideoId, email: string) {
const { user, video } = await getOwnedVideo(videoId);
const normalizedEmail = normalizeEmail(email);
+ if (!normalizedEmail) {
+ return { success: false, error: "Enter a valid email address" } as const;
+ }
const [existingGrant] = await db()
.select({ revokedAt: videoViewerGrants.revokedAt })
@@ -65,7 +68,7 @@ export async function inviteVideoViewer(videoId: Video.VideoId, email: string) {
.limit(1);
if (existingGrant && !existingGrant.revokedAt) {
- return { success: true, alreadyAdded: true, emailSent: false };
+ return { success: true, alreadyAdded: true, emailSent: false } as const;
}
await db()
@@ -101,12 +104,13 @@ export async function inviteVideoViewer(videoId: Video.VideoId, email: string) {
console.error("Failed to email video viewer invitation:", error);
}
- return { success: true, alreadyAdded: false, emailSent };
+ return { success: true, alreadyAdded: false, emailSent } as const;
}
export async function revokeVideoViewer(videoId: Video.VideoId, email: string) {
await getOwnedVideo(videoId);
const normalizedEmail = normalizeEmail(email);
+ if (!normalizedEmail) throw new Error("Enter a valid email address");
await db()
.update(videoViewerGrants)
.set({ revokedAt: new Date() })
diff --git a/apps/web/app/(org)/dashboard/caps/components/SharingDialog.tsx b/apps/web/app/(org)/dashboard/caps/components/SharingDialog.tsx
index 163b39641..b77930c56 100644
--- a/apps/web/app/(org)/dashboard/caps/components/SharingDialog.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/SharingDialog.tsx
@@ -115,6 +115,10 @@ export const SharingDialog: React.FC<SharingDialogProps> = ({
const inviteViewer = useMutation({
mutationFn: () => inviteVideoViewer(capId, viewerEmail),
onSuccess: async (result) => {
+ if (!result.success) {
+ toast.error(result.error);
+ return;
+ }
await viewerGrants.refetch();
router.refresh();
setViewerEmail("");
@@ -473,6 +477,7 @@ export const SharingDialog: React.FC<SharingDialogProps> = ({
type="email"
placeholder="[email protected]"
value={viewerEmail}
+ disabled={inviteViewer.isPending}
onChange={(event) => setViewerEmail(event.target.value)}
/>
<Button