Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): check the space before listing a folder or loading space analytics

Richie McIlroy7204fb735664
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1055952fa..37ca3a971 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -122,6 +122,7 @@ jobs:
- name: Test web React compatibility
run: >-
bun run --cwd apps/web test
+ __tests__/unit/dashboard-analytics-space-access.test.ts
__tests__/unit/embed-video-playback-chrome.test.ts
__tests__/unit/folder-videos.test.ts
__tests__/unit/homepage-demo-accessibility.test.ts
@@ -132,6 +133,7 @@ jobs:
__tests__/unit/playback-store.test.ts
__tests__/unit/seo-demo-videos.test.ts
__tests__/unit/signed-baa-card.test.ts
+ __tests__/unit/space-folder-page-access.test.ts
__tests__/unit/space-page-round-trips.test.ts
__tests__/unit/speed-controller.test.ts
__tests__/unit/summary-editor.test.ts
diff --git a/apps/web/__tests__/unit/dashboard-analytics-space-access.test.ts b/apps/web/__tests__/unit/dashboard-analytics-space-access.test.ts
new file mode 100644
index 000000000..7810ea007
--- /dev/null
+++ b/apps/web/__tests__/unit/dashboard-analytics-space-access.test.ts
@@ -0,0 +1,158 @@
+import type { NextRequest } from "next/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { GET } from "@/app/api/dashboard/analytics/route";
+
+const mocks = vi.hoisted(() => ({
+ query: vi.fn(),
+ getOrgAnalyticsData: vi.fn(),
+}));
+
+vi.mock("server-only", () => ({}));
+vi.mock("@cap/database", async () => {
+ const { drizzle } = await import("drizzle-orm/mysql-proxy");
+ const client = drizzle(mocks.query);
+ return { db: () => client };
+});
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: async () => ({ id: "user-1", activeOrganizationId: "org-1" }),
+}));
+vi.mock("@cap/web-backend", async () => {
+ const { AgentManagement } = await import(
+ "../../../../packages/web-backend/src/AgentManagement"
+ );
+ return { AgentManagement };
+});
+vi.mock("@/lib/server", async () => {
+ const { Effect } = await import("effect");
+ const { Database } = await import(
+ "../../../../packages/web-backend/src/Database"
+ );
+ return {
+ runPromise: <A, E>(
+ effect: import("effect").Effect.Effect<
+ A,
+ E,
+ InstanceType<typeof Database>
+ >,
+ ) => Effect.runPromise(Effect.provide(effect, Database.Default)),
+ };
+});
+vi.mock("@/app/(org)/dashboard/analytics/data", () => ({
+ getOrgAnalyticsData: mocks.getOrgAnalyticsData,
+}));
+
+type SpaceAccessRow = {
+ organizationId: string;
+ createdById: string;
+ privacy: "Public" | "Private";
+ memberRole: string | null;
+ organizationRole: string;
+};
+
+const spaceRow = (overrides: Partial<SpaceAccessRow> = {}) => {
+ const row: SpaceAccessRow = {
+ organizationId: "org-1",
+ createdById: "someone-else",
+ privacy: "Private",
+ memberRole: null,
+ organizationRole: "member",
+ ...overrides,
+ };
+ return [
+ row.organizationId,
+ row.createdById,
+ row.privacy,
+ row.memberRole,
+ row.organizationRole,
+ ];
+};
+
+const request = (params: Record<string, string>) =>
+ ({
+ url: `https://cap.test/api/dashboard/analytics?${new URLSearchParams(params)}`,
+ }) as NextRequest;
+
+beforeEach(() => {
+ mocks.query.mockReset();
+ mocks.query.mockResolvedValue({ rows: [] });
+ mocks.getOrgAnalyticsData.mockReset();
+ mocks.getOrgAnalyticsData.mockResolvedValue({ counts: {} });
+});
+
+describe("dashboard analytics space access", () => {
+ it("loads organization analytics without a space", async () => {
+ const response = await GET(request({ orgId: "org-1" }));
+
+ expect(response.status).toBe(200);
+ expect(mocks.query).not.toHaveBeenCalled();
+ expect(mocks.getOrgAnalyticsData).toHaveBeenCalledWith(
+ "org-1",
+ "7d",
+ undefined,
+ undefined,
+ );
+ });
+
+ it("loads the organization-wide entry without a space lookup", async () => {
+ const response = await GET(request({ orgId: "org-1", spaceId: "org-1" }));
+
+ expect(response.status).toBe(200);
+ expect(mocks.query).not.toHaveBeenCalled();
+ expect(mocks.getOrgAnalyticsData).toHaveBeenCalledWith(
+ "org-1",
+ "7d",
+ "org-1",
+ undefined,
+ );
+ });
+
+ it.each([
+ ["space creator", { createdById: "user-1" }],
+ ["space member", { memberRole: "member" }],
+ ["space admin", { memberRole: "admin" }],
+ ["organization owner", { organizationRole: "owner" }],
+ ["organization admin", { organizationRole: "admin" }],
+ ["organization member on a public space", { privacy: "Public" as const }],
+ ])("allows the %s", async (_, overrides) => {
+ mocks.query.mockResolvedValueOnce({ rows: [spaceRow(overrides)] });
+
+ const response = await GET(
+ request({ orgId: "org-1", spaceId: "space-1", range: "30d" }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(mocks.getOrgAnalyticsData).toHaveBeenCalledWith(
+ "org-1",
+ "30d",
+ "space-1",
+ undefined,
+ );
+ });
+
+ it("rejects an organization member outside a private space", async () => {
+ mocks.query.mockResolvedValueOnce({ rows: [spaceRow()] });
+
+ const response = await GET(request({ orgId: "org-1", spaceId: "space-1" }));
+
+ expect(response.status).toBe(403);
+ expect(mocks.getOrgAnalyticsData).not.toHaveBeenCalled();
+ });
+
+ it("rejects a space the user has no organization membership for", async () => {
+ const response = await GET(request({ orgId: "org-1", spaceId: "space-1" }));
+
+ expect(response.status).toBe(403);
+ expect(mocks.getOrgAnalyticsData).not.toHaveBeenCalled();
+ });
+
+ it("rejects a space from another organization", async () => {
+ mocks.query.mockResolvedValueOnce({
+ rows: [spaceRow({ organizationId: "org-2", createdById: "user-1" })],
+ });
+
+ const response = await GET(request({ orgId: "org-1", spaceId: "space-1" }));
+
+ expect(response.status).toBe(403);
+ expect(mocks.getOrgAnalyticsData).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/__tests__/unit/space-folder-page-access.test.ts b/apps/web/__tests__/unit/space-folder-page-access.test.ts
new file mode 100644
index 000000000..30db47646
--- /dev/null
+++ b/apps/web/__tests__/unit/space-folder-page-access.test.ts
@@ -0,0 +1,151 @@
+import { Folder, type Space } from "@cap/web-domain";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import FolderPage from "@/app/(org)/dashboard/spaces/[spaceId]/folder/[folderId]/page";
+
+const mocks = vi.hoisted(() => ({
+ spaceOrOrg: null as unknown,
+ folder: null as unknown,
+}));
+
+vi.mock("server-only", () => ({}));
+vi.mock("next/navigation", () => ({
+ notFound: () => {
+ throw new Error("NOT_FOUND");
+ },
+}));
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: async () => ({ id: "user-1", activeOrganizationId: "org-1" }),
+}));
+vi.mock("@cap/env", () => ({ serverEnv: () => ({}) }));
+vi.mock("@cap/web-backend", async () => {
+ const { Effect, Layer } = await import("effect");
+ class Spaces extends Effect.Service<Spaces>()("Spaces", {
+ succeed: { getSpaceOrOrg: () => Effect.succeed(mocks.spaceOrOrg) },
+ }) {}
+ return { Spaces, makeCurrentUserLayer: () => Layer.empty };
+});
+vi.mock("@/lib/server", async () => {
+ const { Effect } = await import("effect");
+ const { Spaces } = await import("@cap/web-backend");
+ return {
+ runPromise: <A, E>(
+ effect: import("effect").Effect.Effect<A, E, InstanceType<typeof Spaces>>,
+ ) =>
+ Effect.runPromiseExit(Effect.provide(effect, Spaces.Default)).then(
+ (exit) => {
+ if (exit._tag === "Success") return exit.value;
+ if (exit.cause._tag === "Die") throw exit.cause.defect;
+ throw exit;
+ },
+ ),
+ };
+});
+vi.mock("@/lib/folder", async () => {
+ const { Effect } = await import("effect");
+ return {
+ getChildFolders: () => Effect.succeed([]),
+ getFolderBreadcrumb: () => Effect.succeed([]),
+ getVideosByFolderId: () => Effect.succeed([]),
+ getFolderById: () => Effect.succeed(mocks.folder),
+ };
+});
+vi.mock("@/lib/org-pro", () => ({ isOrganizationOwnerPro: async () => true }));
+vi.mock("@/actions/organization/authorization", () => ({
+ getOrganizationAccess: async () => ({ role: "owner" }),
+}));
+vi.mock("@/actions/organization/space-authorization", () => ({
+ getSpaceAccess: async () => ({ canManage: true }),
+}));
+vi.mock("@/app/(org)/dashboard/_components/CollectionShareControl", () => ({
+ CollectionShareControl: () => null,
+}));
+vi.mock("@/app/(org)/dashboard/caps/components/FoldersSection", () => ({
+ FoldersSection: () => null,
+}));
+vi.mock("@/app/(org)/dashboard/folder/[id]/components", () => ({
+ BreadcrumbItem: () => null,
+ ClientMyCapsLink: () => null,
+ NewSubfolderButton: () => null,
+}));
+vi.mock(
+ "@/app/(org)/dashboard/folder/[id]/components/FolderVideosSection",
+ () => ({ default: () => null }),
+);
+vi.mock(
+ "@/app/(org)/dashboard/spaces/[spaceId]/folder/[folderId]/AddVideosButton",
+ () => ({ default: () => null }),
+);
+
+const SPACE = {
+ variant: "space",
+ space: { id: "space-1", organizationId: "org-1", name: "Design" },
+};
+const ORGANIZATION = {
+ variant: "organization",
+ organization: { id: "org-1", name: "Org", ownerId: "owner-1" },
+};
+
+const folder = (spaceId: string | null) => ({
+ id: "folder-1",
+ name: "Folder",
+ color: "normal",
+ public: false,
+ settings: null,
+ organizationId: "org-1",
+ createdById: "user-1",
+ parentId: null,
+ spaceId,
+});
+
+const load = (spaceId: string) =>
+ FolderPage({
+ params: Promise.resolve({
+ spaceId: spaceId as Space.SpaceIdOrOrganisationId,
+ folderId: Folder.FolderId.make("folder-1"),
+ }),
+ });
+
+beforeEach(() => {
+ mocks.spaceOrOrg = null;
+ mocks.folder = null;
+});
+
+describe("space folder page scope", () => {
+ it("renders a folder that belongs to the space", async () => {
+ mocks.spaceOrOrg = SPACE;
+ mocks.folder = folder("space-1");
+
+ await expect(load("space-1")).resolves.toBeTruthy();
+ });
+
+ it("renders an organization folder on the organization entry", async () => {
+ mocks.spaceOrOrg = ORGANIZATION;
+ mocks.folder = folder("org-1");
+
+ await expect(load("org-1")).resolves.toBeTruthy();
+ });
+
+ it.each([
+ ["another space", "space-2"],
+ ["the organization entry", "org-1"],
+ ["a personal library", null],
+ ])("hides a folder from %s inside a space", async (_, folderSpaceId) => {
+ mocks.spaceOrOrg = SPACE;
+ mocks.folder = folder(folderSpaceId);
+
+ await expect(load("space-1")).rejects.toThrow("NOT_FOUND");
+ });
+
+ it.each([
+ ["a space", "space-1"],
+ ["a personal library", null],
+ ])(
+ "hides a folder from %s on the organization entry",
+ async (_, folderSpaceId) => {
+ mocks.spaceOrOrg = ORGANIZATION;
+ mocks.folder = folder(folderSpaceId);
+
+ await expect(load("org-1")).rejects.toThrow("NOT_FOUND");
+ },
+ );
+});
diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/folder/[folderId]/page.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/folder/[folderId]/page.tsx
index 6327f1f71..0c9d51b21 100644
--- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/folder/[folderId]/page.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/folder/[folderId]/page.tsx
@@ -94,6 +94,7 @@ const FolderPage = async (props: {
// actually belong to the routed space/org — getFolderById is unscoped,
// so a foreign folderId must not surface another collection's settings.
const folderBelongsToContext = currentFolder.spaceId === params.spaceId;
+ if (!folderBelongsToContext) notFound();
const canManageCollection =
folderBelongsToContext &&
(spaceOrOrg.variant === "space"
diff --git a/apps/web/app/api/dashboard/analytics/route.ts b/apps/web/app/api/dashboard/analytics/route.ts
index 4f942b41e..51b2793d2 100644
--- a/apps/web/app/api/dashboard/analytics/route.ts
+++ b/apps/web/app/api/dashboard/analytics/route.ts
@@ -1,13 +1,34 @@
import { getCurrentUser } from "@cap/database/auth/session";
+import { AgentManagement } from "@cap/web-backend";
+import { Space, type User } from "@cap/web-domain";
+import { Effect } from "effect";
import type { NextRequest } from "next/server";
import { getOrgAnalyticsData } from "@/app/(org)/dashboard/analytics/data";
import type { AnalyticsRange } from "@/app/(org)/dashboard/analytics/types";
+import { runPromise } from "@/lib/server";
const RANGE_VALUES: AnalyticsRange[] = ["24h", "7d", "30d", "lifetime"];
export const dynamic = "force-dynamic";
+const canViewSpaceAnalytics = async (
+ userId: User.UserId,
+ orgId: string,
+ spaceId: string,
+) => {
+ if (spaceId === orgId) return true;
+
+ return Effect.flatMap(AgentManagement, (management) =>
+ management.getSpaceAccess(userId, Space.SpaceId.make(spaceId)),
+ ).pipe(
+ Effect.map((access) => access.organizationId === orgId),
+ Effect.catchTag("PolicyDenied", () => Effect.succeed(false)),
+ Effect.provide(AgentManagement.DefaultWithoutDependencies),
+ runPromise,
+ );
+};
+
export async function GET(request: NextRequest) {
const user = await getCurrentUser();
if (!user) return Response.json({ error: "Unauthorized" }, { status: 401 });
@@ -31,6 +52,10 @@ export async function GET(request: NextRequest) {
: "7d";
try {
+ if (spaceId && !(await canViewSpaceAnalytics(user.id, orgId, spaceId))) {
+ return Response.json({ error: "Forbidden" }, { status: 403 });
+ }
+
const data = await getOrgAnalyticsData(orgId, range, spaceId, capId);
return Response.json({ data });
} catch (error) {