Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Check video access in getVideoAnalytics server action
Richie McIlroy2a4279321a61
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 37ca3a971..3aa865d3b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -139,6 +139,7 @@ jobs:__tests__/unit/summary-editor.test.ts__tests__/unit/sso-login-pages.test.ts__tests__/unit/transcript-numbers.test.ts+ __tests__/unit/video-analytics-access.test.ts- name: Typecheckrun: bun run typecheckdiff --git a/apps/web/__tests__/unit/share-page-loading.test.ts b/apps/web/__tests__/unit/share-page-loading.test.tsindex 85824cd42..9c20da562 100644--- a/apps/web/__tests__/unit/share-page-loading.test.ts+++ b/apps/web/__tests__/unit/share-page-loading.test.ts@@ -70,8 +70,8 @@ vi.mock("next/navigation", () => ({throw new Error("NOT_FOUND");},}));-vi.mock("@/actions/videos/get-analytics", () => ({- getVideoAnalytics: async () => ({ count: 12 }),+vi.mock("@/lib/video-view-count", () => ({+ getVideoViewCount: async () => ({ count: 12 }),}));vi.mock("@/app/(org)/dashboard/dashboard-data", () => ({getDashboardSpacesData: async () => [],diff --git a/apps/web/__tests__/unit/video-analytics-access.test.ts b/apps/web/__tests__/unit/video-analytics-access.test.tsnew file mode 100644index 000000000..c408329e9--- /dev/null+++ b/apps/web/__tests__/unit/video-analytics-access.test.ts@@ -0,0 +1,272 @@+import type { VideosPolicyDeps } from "@cap/web-backend";+import {+ type CurrentUser,+ type Organisation,+ type User,+ Video,+} from "@cap/web-domain";+import { Effect, Option } from "effect";+import { beforeEach, describe, expect, it, vi } from "vitest";++const VIDEO_ID = "analytics-video" as Video.VideoId;+const OWNER_ID = "owner-1" as User.UserId;+const VIEWER_ID = "viewer-1" as User.UserId;+const ORG_ID = "org-1" as Organisation.OrganisationId;++type Scenario = {+ exists: boolean;+ public: boolean;+ password: Option.Option<string>;+ spacePasswords: string[];+ orgMembership: boolean;+ spaceMembership: boolean;+ allowedEmailDomain: Option.Option<string>;+ viewerGrantEmail?: string;+ user: Option.Option<CurrentUser["Type"]>;+ verifiedPasswords: string[];+};++const mocks = vi.hoisted(() => ({+ scenario: {} as Scenario,+ viewCount: vi.fn(),+}));++const makeVideo = () =>+ Video.Video.make({+ id: VIDEO_ID,+ ownerId: OWNER_ID,+ orgId: ORG_ID,+ name: "Recording",+ public: mocks.scenario.public,+ source: { type: "desktopMP4" },+ metadata: Option.none(),+ bucketId: Option.none(),+ storageIntegrationId: Option.none(),+ folderId: Option.none(),+ transcriptionStatus: Option.none(),+ width: Option.none(),+ height: Option.none(),+ duration: Option.none(),+ createdAt: new Date(),+ updatedAt: new Date(),+ });++const makeDeps = (): VideosPolicyDeps => ({+ repo: {+ getById: () =>+ Effect.sync(() =>+ mocks.scenario.exists+ ? Option.some([makeVideo(), mocks.scenario.password] as const)+ : Option.none(),+ ),+ hasViewerGrant: (_, email) =>+ Effect.succeed(email === mocks.scenario.viewerGrantEmail),+ },+ orgsRepo: {+ membershipForVideo: () =>+ Effect.sync(() =>+ mocks.scenario.orgMembership ? [{ membershipId: "member" }] : [],+ ),+ allowedEmailDomain: () =>+ Effect.sync(() => mocks.scenario.allowedEmailDomain),+ },+ spacesRepo: {+ membershipForVideo: () =>+ Effect.sync(() =>+ mocks.scenario.spaceMembership+ ? Option.some({ membershipId: "space-member" })+ : Option.none(),+ ),+ passwordsForVideo: () =>+ Effect.sync(() =>+ mocks.scenario.spacePasswords.map((password) => ({ password })),+ ),+ },+});++vi.mock("@cap/database", () => ({+ db: () => ({+ select: () => ({+ from: () => ({+ where: () => ({+ limit: async () => (mocks.scenario.exists ? [{ id: VIDEO_ID }] : []),+ }),+ }),+ }),+ }),+}));++vi.mock("@cap/web-backend", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@cap/web-backend")>();+ const { Effect, Option } = await import("effect");+ const { CurrentUser, Video } = await import("@cap/web-domain");+ class VideosPolicy extends Effect.Service<VideosPolicy>()("VideosPolicy", {+ sync: () => ({+ canView: (id: Video.VideoId) => actual.buildCanView(makeDeps(), id),+ }),+ }) {}+ return {+ VideosPolicy,+ provideOptionalAuth: <A, E, R>(app: Effect.Effect<A, E, R>) => {+ const withPolicy = app.pipe(+ Effect.provide(VideosPolicy.Default),+ Effect.provideService(Video.VideoPasswordAttachment, {+ passwords: mocks.scenario.verifiedPasswords,+ }),+ );+ return Option.match(mocks.scenario.user, {+ onNone: () => withPolicy,+ onSome: (user) => Effect.provideService(withPolicy, CurrentUser, user),+ });+ },+ };+});++vi.mock("@/lib/server", () => ({ runPromiseExit: Effect.runPromiseExit }));+vi.mock("@/lib/video-view-count", () => ({+ getVideoViewCount: mocks.viewCount,+}));++const { getVideoAnalytics } = await import("@/actions/videos/get-analytics");++const makeUser = (email: string, id: User.UserId = VIEWER_ID) =>+ Option.some<CurrentUser["Type"]>({+ id,+ email,+ activeOrganizationId: ORG_ID,+ iconUrlOrKey: Option.none(),+ });++const expectAllowed = async (options?: { rangeDays?: number }) => {+ await expect(getVideoAnalytics(VIDEO_ID, options)).resolves.toEqual({+ count: 7,+ });+ expect(mocks.viewCount).toHaveBeenCalledWith(VIDEO_ID, options);+};++const expectDenied = async () => {+ await expect(getVideoAnalytics(VIDEO_ID)).rejects.toThrow("Video not found");+ expect(mocks.viewCount).not.toHaveBeenCalled();+};++beforeEach(() => {+ mocks.scenario = {+ exists: true,+ public: true,+ password: Option.none(),+ spacePasswords: [],+ orgMembership: false,+ spaceMembership: false,+ allowedEmailDomain: Option.none(),+ viewerGrantEmail: undefined,+ user: Option.none(),+ verifiedPasswords: [],+ };+ mocks.viewCount.mockReset();+ mocks.viewCount.mockResolvedValue({ count: 7 });+});++describe("getVideoAnalytics access", () => {+ it("returns the count to anonymous viewers of public videos", async () => {+ await expectAllowed();+ });++ it("passes the range option through", async () => {+ await expectAllowed({ rangeDays: 7 });+ });++ it("returns the count to the owner of a private video", async () => {+ mocks.scenario.public = false;+ mocks.scenario.user = makeUser("[email protected]", OWNER_ID);+ await expectAllowed();+ });++ it("returns the count to org members of a private video", async () => {+ mocks.scenario.public = false;+ mocks.scenario.orgMembership = true;+ mocks.scenario.user = makeUser("[email protected]");+ await expectAllowed();+ });++ it("returns the count to space members of a private video", async () => {+ mocks.scenario.public = false;+ mocks.scenario.spaceMembership = true;+ mocks.scenario.user = makeUser("[email protected]");+ await expectAllowed();+ });++ it("returns the count to invited viewers of a private video", async () => {+ mocks.scenario.public = false;+ mocks.scenario.viewerGrantEmail = "[email protected]";+ mocks.scenario.user = makeUser("[email protected]");+ await expectAllowed();+ });++ it("returns the count for a password video with a verified cookie", async () => {+ mocks.scenario.password = Option.some("hash-1");+ mocks.scenario.verifiedPasswords = ["hash-1"];+ await expectAllowed();+ });++ it("returns the count for a space password with a verified cookie", async () => {+ mocks.scenario.spacePasswords = ["space-hash"];+ mocks.scenario.verifiedPasswords = ["space-hash"];+ await expectAllowed();+ });++ it("returns the count when the viewer matches the email restriction", async () => {+ mocks.scenario.allowedEmailDomain = Option.some("example.com");+ mocks.scenario.user = makeUser("[email protected]");+ await expectAllowed();+ });++ it("denies anonymous viewers of private videos", async () => {+ mocks.scenario.public = false;+ await expectDenied();+ });++ it("denies signed-in users without access to a private video", async () => {+ mocks.scenario.public = false;+ mocks.scenario.user = makeUser("[email protected]");+ await expectDenied();+ });++ it("denies password videos without a verified cookie", async () => {+ mocks.scenario.password = Option.some("hash-1");+ await expectDenied();+ });++ it("denies password videos with a wrong verified password", async () => {+ mocks.scenario.password = Option.some("hash-1");+ mocks.scenario.verifiedPasswords = ["other-hash"];+ await expectDenied();+ });++ it("denies space password videos without a verified cookie", async () => {+ mocks.scenario.spacePasswords = ["space-hash"];+ mocks.scenario.orgMembership = true;+ mocks.scenario.user = makeUser("[email protected]");+ await expectDenied();+ });++ it("denies anonymous viewers when an email restriction is active", async () => {+ mocks.scenario.allowedEmailDomain = Option.some("example.com");+ await expectDenied();+ });++ it("denies viewers outside the email restriction", async () => {+ mocks.scenario.allowedEmailDomain = Option.some("example.com");+ mocks.scenario.user = makeUser("[email protected]");+ await expectDenied();+ });++ it("does not query analytics for unknown videos", async () => {+ mocks.scenario.exists = false;+ await expectDenied();+ });++ it("rejects an empty video id", async () => {+ await expect(getVideoAnalytics("")).rejects.toThrow("Video ID is required");+ expect(mocks.viewCount).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/__tests__/unit/video-edit-processing.test.ts b/apps/web/__tests__/unit/video-edit-processing.test.tsindex db5fc1917..665526900 100644--- a/apps/web/__tests__/unit/video-edit-processing.test.ts+++ b/apps/web/__tests__/unit/video-edit-processing.test.ts@@ -99,7 +99,7 @@ vi.mock("next/navigation", () => ({throw new Error("NEXT_NOT_FOUND");},}));-vi.mock("@/actions/videos/get-analytics", () => ({}));+vi.mock("@/lib/video-view-count", () => ({}));vi.mock("@/app/(org)/dashboard/dashboard-data", () => ({}));vi.mock("@/lib/ai/provider", () => ({}));vi.mock("@/lib/desktop-segments-recovery", () => ({}));diff --git a/apps/web/actions/videos/get-analytics.ts b/apps/web/actions/videos/get-analytics.tsindex 83726d52e..9e47df0f9 100644--- a/apps/web/actions/videos/get-analytics.ts+++ b/apps/web/actions/videos/get-analytics.ts@@ -2,99 +2,38 @@import { db } from "@cap/database";import { videos } from "@cap/database/schema";-import { Tinybird } from "@cap/web-backend";-import { Video } from "@cap/web-domain";+import { provideOptionalAuth, VideosPolicy } from "@cap/web-backend";+import { Policy, Video } from "@cap/web-domain";import { eq } from "drizzle-orm";-import { Effect } from "effect";-import { runPromise } from "@/lib/server";--const DAY_IN_MS = 24 * 60 * 60 * 1000;-const MIN_RANGE_DAYS = 1;-const MAX_RANGE_DAYS = 90;-const DEFAULT_RANGE_DAYS = MAX_RANGE_DAYS;--// Escape backslashes BEFORE quotes: ClickHouse honors C-style `\'` inside-// single-quoted literals, so doubling quotes alone lets a trailing backslash-// neutralise the doubled quote and break out of the string (SQL injection).-const escapeLiteral = (value: string) =>- value.replace(/\\/g, "\\\\").replace(/'/g, "''");-const formatDate = (date: Date) => date.toISOString().slice(0, 10);-const formatDateTime = (date: Date) =>- date.toISOString().slice(0, 19).replace("T", " ");-const buildConditions = (clauses: Array<string | undefined>) =>- clauses.filter((clause): clause is string => Boolean(clause)).join(" AND ");--const normalizeRangeDays = (rangeDays?: number) => {- if (!Number.isFinite(rangeDays)) return DEFAULT_RANGE_DAYS;- const normalized = Math.floor(rangeDays as number);- if (normalized <= 0) return DEFAULT_RANGE_DAYS;- return Math.max(MIN_RANGE_DAYS, Math.min(normalized, MAX_RANGE_DAYS));-};--interface GetVideoAnalyticsOptions {- rangeDays?: number;-}+import { Effect, Exit } from "effect";+import * as EffectRuntime from "@/lib/server";+import {+ getVideoViewCount,+ type VideoViewCountOptions,+} from "@/lib/video-view-count";export async function getVideoAnalytics(videoId: string,- options?: GetVideoAnalyticsOptions,+ options?: VideoViewCountOptions,) {if (!videoId) throw new Error("Video ID is required");- const [{ orgId } = { orgId: null }] = await db()- .select({ orgId: videos.orgId })- .from(videos)- .where(eq(videos.id, Video.VideoId.make(videoId)))- .limit(1);-- return runPromise(- Effect.gen(function* () {- const tinybird = yield* Tinybird;-- const rangeDays = normalizeRangeDays(options?.rangeDays);- const now = new Date();- const from = new Date(now.getTime() - rangeDays * DAY_IN_MS);- const pathname = `/s/${videoId}`;- const aggregateConditions = [- orgId ? `tenant_id = '${escapeLiteral(orgId)}'` : undefined,- `pathname = '${escapeLiteral(pathname)}'`,- `date BETWEEN toDate('${formatDate(from)}') AND toDate('${formatDate(now)}')`,- ];- const aggregateSql = `SELECT coalesce(uniqMerge(visits), 0) AS views FROM analytics_pages_mv WHERE ${buildConditions(aggregateConditions)}`;-- const rawConditions = [- "action = 'page_hit'",- orgId ? `tenant_id = '${escapeLiteral(orgId)}'` : undefined,- `pathname = '${escapeLiteral(pathname)}'`,- `timestamp BETWEEN toDateTime('${formatDateTime(from)}') AND toDateTime('${formatDateTime(now)}')`,- ];- const rawSql = `SELECT coalesce(uniq(session_id), 0) AS views FROM analytics_events WHERE ${buildConditions(rawConditions)}`;-- const querySql = (sql: string) =>- tinybird.querySql<{ views: number }>(sql).pipe(- Effect.catchAll((e) => {- console.error("tinybird sql error", e);- return Effect.succeed({ data: [] });- }),- );+ const id = Video.VideoId.make(videoId);- const aggregateResult = yield* querySql(aggregateSql);+ const exit = await Effect.gen(function* () {+ const videosPolicy = yield* VideosPolicy;+ return yield* Effect.promise(() =>+ db()+ .select({ id: videos.id })+ .from(videos)+ .where(eq(videos.id, id))+ .limit(1),+ ).pipe(Policy.withPublicPolicy(videosPolicy.canView(id)));+ }).pipe(provideOptionalAuth, EffectRuntime.runPromiseExit);- const fallbackResult = aggregateResult.data?.length- ? aggregateResult- : yield* querySql(rawSql);+ if (Exit.isFailure(exit) || !exit.value[0]) {+ throw new Error("Video not found");+ }- const data = fallbackResult?.data ?? [];- const firstItem = data[0];- const count =- typeof firstItem === "number"- ? firstItem- : typeof firstItem === "object" &&- firstItem !== null &&- "views" in firstItem- ? Number(firstItem.views ?? 0)- : 0;- return { count: Number.isFinite(count) ? count : 0 };- }),- );+ return getVideoViewCount(videoId, options);}diff --git a/apps/web/app/api/analytics/route.ts b/apps/web/app/api/analytics/route.tsindex d3629ed33..3643b3b13 100644--- a/apps/web/app/api/analytics/route.ts+++ b/apps/web/app/api/analytics/route.ts@@ -5,8 +5,8 @@ import { Policy, Video } from "@cap/web-domain";import { eq } from "drizzle-orm";import { Effect, Exit } from "effect";import type { NextRequest } from "next/server";-import { getVideoAnalytics } from "@/actions/videos/get-analytics";import * as EffectRuntime from "@/lib/server";+import { getVideoViewCount } from "@/lib/video-view-count";const parseRangeParam = (value: string | null) => {if (!value) return undefined;@@ -51,7 +51,7 @@ export async function GET(request: NextRequest) {try {console.log("videoId", videoId);- const result = await getVideoAnalytics(videoId, { rangeDays });+ const result = await getVideoViewCount(videoId, { rangeDays });console.log("result", result);return Response.json({ count: result.count }, { status: 200 });} catch (error) {diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsxindex f853e62c4..1c82858a6 100644--- a/apps/web/app/s/[videoId]/page.tsx+++ b/apps/web/app/s/[videoId]/page.tsx@@ -38,7 +38,6 @@ import type { Metadata } from "next";import { headers } from "next/headers";import { notFound } from "next/navigation";import { after } from "next/server";-import { getVideoAnalytics } from "@/actions/videos/get-analytics";import {getDashboardSpacesData,type OrganizationSettings,@@ -79,6 +78,7 @@ import {areEditSpecsEquivalent,createIdentityEditSpec,} from "@/lib/video-edits";+import { getVideoViewCount } from "@/lib/video-view-count";import { optionFromTOrFirst } from "@/utils/effect";import { isAiGenerationEnabled } from "@/utils/flags";import {@@ -722,7 +722,7 @@ async function AuthorizedContent({);}).pipe(EffectRuntime.runPromise);- const viewsPromise = getVideoAnalytics(videoId).then((v) => v.count);+ const viewsPromise = getVideoViewCount(videoId).then((v) => v.count);const videoOrganizationRolePromise = (async () => {if (!userId) return null;diff --git a/apps/web/lib/video-view-count.ts b/apps/web/lib/video-view-count.tsnew file mode 100644index 000000000..b43273d7e--- /dev/null+++ b/apps/web/lib/video-view-count.ts@@ -0,0 +1,98 @@+import { db } from "@cap/database";+import { videos } from "@cap/database/schema";+import { Tinybird } from "@cap/web-backend";+import { Video } from "@cap/web-domain";+import { eq } from "drizzle-orm";+import { Effect } from "effect";+import { runPromise } from "@/lib/server";++const DAY_IN_MS = 24 * 60 * 60 * 1000;+const MIN_RANGE_DAYS = 1;+const MAX_RANGE_DAYS = 90;+const DEFAULT_RANGE_DAYS = MAX_RANGE_DAYS;++// Escape backslashes BEFORE quotes: ClickHouse honors C-style `\'` inside+// single-quoted literals, so doubling quotes alone lets a trailing backslash+// neutralise the doubled quote and break out of the string (SQL injection).+const escapeLiteral = (value: string) =>+ value.replace(/\\/g, "\\\\").replace(/'/g, "''");+const formatDate = (date: Date) => date.toISOString().slice(0, 10);+const formatDateTime = (date: Date) =>+ date.toISOString().slice(0, 19).replace("T", " ");+const buildConditions = (clauses: Array<string | undefined>) =>+ clauses.filter((clause): clause is string => Boolean(clause)).join(" AND ");++const normalizeRangeDays = (rangeDays?: number) => {+ if (!Number.isFinite(rangeDays)) return DEFAULT_RANGE_DAYS;+ const normalized = Math.floor(rangeDays as number);+ if (normalized <= 0) return DEFAULT_RANGE_DAYS;+ return Math.max(MIN_RANGE_DAYS, Math.min(normalized, MAX_RANGE_DAYS));+};++export interface VideoViewCountOptions {+ rangeDays?: number;+}++export async function getVideoViewCount(+ videoId: string,+ options?: VideoViewCountOptions,+) {+ if (!videoId) throw new Error("Video ID is required");++ const [{ orgId } = { orgId: null }] = await db()+ .select({ orgId: videos.orgId })+ .from(videos)+ .where(eq(videos.id, Video.VideoId.make(videoId)))+ .limit(1);++ return runPromise(+ Effect.gen(function* () {+ const tinybird = yield* Tinybird;++ const rangeDays = normalizeRangeDays(options?.rangeDays);+ const now = new Date();+ const from = new Date(now.getTime() - rangeDays * DAY_IN_MS);+ const pathname = `/s/${videoId}`;+ const aggregateConditions = [+ orgId ? `tenant_id = '${escapeLiteral(orgId)}'` : undefined,+ `pathname = '${escapeLiteral(pathname)}'`,+ `date BETWEEN toDate('${formatDate(from)}') AND toDate('${formatDate(now)}')`,+ ];+ const aggregateSql = `SELECT coalesce(uniqMerge(visits), 0) AS views FROM analytics_pages_mv WHERE ${buildConditions(aggregateConditions)}`;++ const rawConditions = [+ "action = 'page_hit'",+ orgId ? `tenant_id = '${escapeLiteral(orgId)}'` : undefined,+ `pathname = '${escapeLiteral(pathname)}'`,+ `timestamp BETWEEN toDateTime('${formatDateTime(from)}') AND toDateTime('${formatDateTime(now)}')`,+ ];+ const rawSql = `SELECT coalesce(uniq(session_id), 0) AS views FROM analytics_events WHERE ${buildConditions(rawConditions)}`;++ const querySql = (sql: string) =>+ tinybird.querySql<{ views: number }>(sql).pipe(+ Effect.catchAll((e) => {+ console.error("tinybird sql error", e);+ return Effect.succeed({ data: [] });+ }),+ );++ const aggregateResult = yield* querySql(aggregateSql);++ const fallbackResult = aggregateResult.data?.length+ ? aggregateResult+ : yield* querySql(rawSql);++ const data = fallbackResult?.data ?? [];+ const firstItem = data[0];+ const count =+ typeof firstItem === "number"+ ? firstItem+ : typeof firstItem === "object" &&+ firstItem !== null &&+ "views" in firstItem+ ? Number(firstItem.views ?? 0)+ : 0;+ return { count: Number.isFinite(count) ? count : 0 };+ }),+ );+}