Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): record share views under the video's own org and path

Richie McIlroy0bdebc697c19
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 593ffef9a..23a256afe 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -128,6 +128,7 @@ jobs:
- name: Test web React compatibility
run: >-
bun run --cwd apps/web test
+ __tests__/unit/analytics-track-route.test.ts
__tests__/unit/caps-keyboard.test.ts
__tests__/unit/comment-composer-composition.test.ts
__tests__/unit/dashboard-analytics-cap-access.test.ts
diff --git a/apps/web/__tests__/unit/analytics-track-route.test.ts b/apps/web/__tests__/unit/analytics-track-route.test.ts
new file mode 100644
index 000000000..881258636
--- /dev/null
+++ b/apps/web/__tests__/unit/analytics-track-route.test.ts
@@ -0,0 +1,162 @@
+import type { NextRequest } from "next/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const VIDEO_ID = "video-1";
+const ORG_ID = "org-1";
+const OWNER_ID = "owner-1";
+
+const mocks = vi.hoisted(() => ({
+ video: undefined as Record<string, unknown> | undefined,
+ userId: null as string | null,
+ appendEvents: vi.fn(),
+}));
+
+vi.mock("server-only", () => ({}));
+
+vi.mock("@cap/database", () => ({
+ db: () => ({
+ select: () => ({
+ from: () => ({
+ leftJoin: () => ({
+ where: () => ({
+ limit: async () => (mocks.video ? [mocks.video] : []),
+ }),
+ }),
+ }),
+ }),
+ }),
+}));
+
+vi.mock("@cap/database/auth/request-site", () => ({
+ isCrossSiteCookieWrite: () => false,
+}));
+
+vi.mock("@cap/web-backend", async () => {
+ const { Context, Effect } = await import("effect");
+ const { CurrentUser } = await import("@cap/web-domain");
+ const Tinybird = Context.GenericTag<{
+ appendEvents: (events: unknown[]) => Effect.Effect<void>;
+ }>("Tinybird");
+ return {
+ Tinybird,
+ provideOptionalAuth: (app: Effect.Effect<unknown, unknown, never>) => {
+ const withTinybird = app.pipe(
+ Effect.provideService(Tinybird, {
+ appendEvents: (events) =>
+ Effect.sync(() => mocks.appendEvents(events)),
+ }),
+ );
+ return mocks.userId
+ ? withTinybird.pipe(
+ Effect.provideService(CurrentUser, {
+ id: mocks.userId,
+ email: "[email protected]",
+ activeOrganizationId: ORG_ID,
+ } as never),
+ )
+ : withTinybird;
+ },
+ };
+});
+
+vi.mock("@/lib/server", async () => {
+ const { Effect } = await import("effect");
+ return { runPromise: Effect.runPromise };
+});
+
+vi.mock("@/lib/Notification", () => ({
+ createAnonymousViewNotification: vi.fn(async () => undefined),
+ sendFirstViewEmail: vi.fn(async () => undefined),
+}));
+
+const { POST } = await import("@/app/api/analytics/track/route");
+
+const track = (body: Record<string, unknown>) =>
+ POST(
+ new Request("https://cap.so/api/analytics/track", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }) as unknown as NextRequest,
+ );
+
+const recordedEvents = () =>
+ mocks.appendEvents.mock.calls.flatMap(
+ ([events]) => events as Array<Record<string, unknown>>,
+ );
+
+describe("POST /api/analytics/track", () => {
+ beforeEach(() => {
+ mocks.appendEvents.mockClear();
+ mocks.userId = null;
+ mocks.video = {
+ orgId: ORG_ID,
+ ownerId: OWNER_ID,
+ firstViewEmailSentAt: new Date("2025-01-01T00:00:00Z"),
+ videoName: "Demo",
+ createdAt: new Date("2025-01-01T00:00:00Z"),
+ updatedAt: new Date("2025-01-01T00:00:00Z"),
+ activeUploadVideoId: null,
+ };
+ });
+
+ it("records the view under the video's own org and share path", async () => {
+ const response = await track({
+ videoId: VIDEO_ID,
+ orgId: "someone-elses-org",
+ ownerId: "someone-else",
+ pathname: "/s/a-different-video",
+ hostname: "attacker.example",
+ sessionId: "session-1",
+ });
+
+ expect(response.status).toBe(200);
+ expect(recordedEvents()).toEqual([
+ expect.objectContaining({
+ tenant_id: ORG_ID,
+ video_id: VIDEO_ID,
+ pathname: `/s/${VIDEO_ID}`,
+ session_id: "session-1",
+ }),
+ ]);
+ });
+
+ it("does not record views for videos that do not exist", async () => {
+ mocks.video = undefined;
+
+ const response = await track({
+ videoId: "made-up-video",
+ orgId: ORG_ID,
+ pathname: `/s/${VIDEO_ID}`,
+ sessionId: "session-1",
+ });
+
+ expect(response.status).toBe(200);
+ expect(recordedEvents()).toEqual([]);
+ });
+
+ it("does not record the owner's own views", async () => {
+ mocks.userId = OWNER_ID;
+
+ await track({ videoId: VIDEO_ID, sessionId: "session-1" });
+
+ expect(recordedEvents()).toEqual([]);
+ });
+
+ it("keeps a client timestamp close to now and replaces one far from it", async () => {
+ const recent = new Date(Date.now() - 30_000).toISOString();
+ await track({ videoId: VIDEO_ID, occurredAt: recent });
+
+ const before = Date.now();
+ await track({ videoId: VIDEO_ID, occurredAt: "2020-01-01T00:00:00Z" });
+ await track({ videoId: VIDEO_ID, occurredAt: "not a date" });
+
+ const [kept, backdated, invalid] = recordedEvents();
+ expect(kept?.timestamp).toBe(recent);
+ for (const event of [backdated, invalid]) {
+ expect(Date.parse(event?.timestamp as string)).toBeGreaterThanOrEqual(
+ before,
+ );
+ }
+ });
+});
diff --git a/apps/web/app/api/analytics/track/route.ts b/apps/web/app/api/analytics/track/route.ts
index 01746e860..d6aa452a9 100644
--- a/apps/web/app/api/analytics/track/route.ts
+++ b/apps/web/app/api/analytics/track/route.ts
@@ -17,16 +17,22 @@ import { runPromise } from "@/lib/server";
interface TrackPayload {
videoId: string;
- orgId?: string | null;
- ownerId?: string | null;
sessionId?: string;
- pathname?: string;
- hostname?: string | null;
userAgent?: string;
occurredAt?: string;
}
const VIEW_TRACKING_DELAY_MS = 2 * 60 * 1000;
+const MAX_CLIENT_CLOCK_SKEW_MS = 5 * 60 * 1000;
+
+const viewTimestamp = (occurredAt: unknown, now: number) => {
+ const time =
+ typeof occurredAt === "string" ? Date.parse(occurredAt) : Number.NaN;
+ return Number.isFinite(time) &&
+ Math.abs(time - now) <= MAX_CLIENT_CLOCK_SKEW_MS
+ ? new Date(time)
+ : new Date(now);
+};
const sanitizeString = (value?: string | null) => {
const trimmed = value?.trim();
@@ -69,7 +75,7 @@ export async function POST(request: NextRequest) {
const osName = parser.getOS().name ?? "unknown";
const deviceType = parser.getDevice().type ?? "desktop";
- const timestamp = body.occurredAt ? new Date(body.occurredAt) : new Date();
+ const timestamp = viewTimestamp(body.occurredAt, Date.now());
const country =
sanitizeString(request.headers.get("x-vercel-ip-country")) || "";
@@ -80,13 +86,6 @@ export async function POST(request: NextRequest) {
decodeUrlEncodedHeaderValue(request.headers.get("x-vercel-ip-city")),
) || "";
- const hostname =
- sanitizeString(body.hostname) ||
- sanitizeString(request.nextUrl.hostname) ||
- "";
-
- const pathname = body.pathname ?? `/s/${body.videoId}`;
-
await runPromise(
Effect.gen(function* () {
const maybeUser = yield* Effect.serviceOption(CurrentUser);
@@ -108,6 +107,7 @@ export async function POST(request: NextRequest) {
const [videoRecord] = yield* Effect.tryPromise(() =>
db()
.select({
+ orgId: videos.orgId,
ownerId: videos.ownerId,
firstViewEmailSentAt: videos.firstViewEmailSentAt,
videoName: videos.name,
@@ -123,6 +123,7 @@ export async function POST(request: NextRequest) {
Effect.orElseSucceed(
() =>
[] as {
+ orgId: string;
ownerId: string;
firstViewEmailSentAt: Date | null;
videoName: string;
@@ -133,24 +134,17 @@ export async function POST(request: NextRequest) {
),
);
- if (videoRecord && userId === videoRecord.ownerId) {
+ if (!videoRecord || userId === videoRecord.ownerId) {
return;
}
if (
- videoRecord &&
- (videoRecord.activeUploadVideoId ||
- Date.now() - videoRecord.updatedAt.getTime() < VIEW_TRACKING_DELAY_MS)
+ videoRecord.activeUploadVideoId ||
+ Date.now() - videoRecord.updatedAt.getTime() < VIEW_TRACKING_DELAY_MS
) {
return;
}
- const tenantId =
- body.orgId ||
- videoRecord?.ownerId ||
- body.ownerId ||
- (hostname ? `domain:${hostname}` : "public");
-
const tinybird = yield* Tinybird;
yield* tinybird.appendEvents([
{
@@ -158,9 +152,9 @@ export async function POST(request: NextRequest) {
session_id: sessionId ?? "anon",
action: "page_hit",
version: "1.0",
- tenant_id: tenantId,
+ tenant_id: videoRecord.orgId || videoRecord.ownerId,
video_id: body.videoId,
- pathname,
+ pathname: `/s/${body.videoId}`,
country,
region,
city,
@@ -171,8 +165,7 @@ export async function POST(request: NextRequest) {
},
]);
- const isNewVideo =
- videoRecord && videoRecord.createdAt >= ANON_NOTIF_CUTOFF;
+ const isNewVideo = videoRecord.createdAt >= ANON_NOTIF_CUTOFF;
const shouldSendFirstViewEmail =
isNewVideo && !videoRecord.firstViewEmailSentAt;