Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): emit share metadata on the verified custom domain

Dave Fajardo7a75d982bb53
diff --git a/apps/web/__tests__/unit/share-web-url.test.ts b/apps/web/__tests__/unit/share-web-url.test.ts
new file mode 100644
index 000000000..3222f168e
--- /dev/null
+++ b/apps/web/__tests__/unit/share-web-url.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from "vitest";
+import {
+ isDefaultShareHostname,
+ requestShareHostname,
+} from "@/lib/share-web-url";
+
+const headersFrom = (init: Record<string, string>) => new Headers(init);
+
+describe("requestShareHostname", () => {
+ it("reads the host header", () => {
+ expect(requestShareHostname(headersFrom({ host: "cap.so" }))).toBe("cap.so");
+ });
+
+ it("prefers the forwarded host set by the proxy", () => {
+ const headers = headersFrom({
+ host: "cap-web.vercel.app",
+ "x-forwarded-host": "looms.example.com",
+ });
+
+ expect(requestShareHostname(headers)).toBe("looms.example.com");
+ });
+
+ it("takes the first entry of a forwarded host list", () => {
+ const headers = headersFrom({
+ "x-forwarded-host": "looms.example.com, cap.so",
+ });
+
+ expect(requestShareHostname(headers)).toBe("looms.example.com");
+ });
+
+ it("lowercases the host and drops the port", () => {
+ expect(requestShareHostname(headersFrom({ host: "LocalHost:3000" }))).toBe(
+ "localhost",
+ );
+ });
+
+ it("returns an empty string when no host header is present", () => {
+ expect(requestShareHostname(headersFrom({}))).toBe("");
+ });
+});
+
+describe("isDefaultShareHostname", () => {
+ it.each(["cap.so", "cap.link", "localhost", "127.0.0.1"])(
+ "treats %s as a default host",
+ (hostname) => {
+ expect(isDefaultShareHostname(hostname, "https://cap.so")).toBe(true);
+ },
+ );
+
+ it("matches the configured web URL host", () => {
+ expect(isDefaultShareHostname("cap.example.com", "https://cap.example.com")).toBe(
+ true,
+ );
+ });
+
+ it("rejects a custom domain", () => {
+ expect(isDefaultShareHostname("looms.example.com", "https://cap.so")).toBe(
+ false,
+ );
+ });
+
+ it("falls back to the default host when the host is missing", () => {
+ expect(isDefaultShareHostname("", "https://cap.so")).toBe(true);
+ });
+
+ it("falls back to the default host when the web URL is unparsable", () => {
+ expect(isDefaultShareHostname("looms.example.com", "not-a-url")).toBe(true);
+ });
+});
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index 3c7251377..56546aa61 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -14,7 +14,7 @@ import {
videoUploads,
} from "@cap/database/schema";
import type { VideoMetadata } from "@cap/database/types";
-import { buildEnv, serverEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
import { Logo } from "@cap/ui";
import { userIsPro } from "@cap/utils";
import {
@@ -56,6 +56,7 @@ import * as EffectRuntime from "@/lib/server";
import { runPromise } from "@/lib/server";
import { getSharePageBranding } from "@/lib/share-branding";
import { buildShareVideoMetadata } from "@/lib/share-video-metadata";
+import { resolveShareWebUrl } from "@/lib/share-web-url";
import {
isIframelyCrawlerUserAgent,
isSocialCrawlerUserAgent,
@@ -235,6 +236,13 @@ export async function generateMetadata(
const shouldAdvertiseIframelyPlayer =
isIframelyCrawlerUserAgent(requestUserAgent) &&
(await getPublicShareVideo(videoId).catch(() => null)) !== null;
+ // Share pages also serve verified custom domains. Metadata has to point at
+ // the host the visitor used, or Slack drops the preview image.
+ const webUrl = await resolveShareWebUrl(headersList);
+ const ogImageUrl = new URL(
+ `/api/video/og?videoId=${videoId}`,
+ webUrl,
+ ).toString();
return Effect.flatMap(Videos, (v) => v.getByIdForViewing(videoId)).pipe(
Effect.map(
@@ -253,7 +261,7 @@ export async function generateMetadata(
videoId,
name: video.name,
sourceType: video.source.type,
- webUrl: buildEnv.NEXT_PUBLIC_WEB_URL,
+ webUrl,
advertiseIframelyPlayer: shouldAdvertiseIframelyPlayer,
}),
robots: canRenderSocialPreview
@@ -269,16 +277,7 @@ export async function generateMetadata(
title: "Cap: This video is restricted",
description: "This video has restricted access.",
openGraph: {
- images: [
- {
- url: new URL(
- `/api/video/og?videoId=${videoId}`,
- buildEnv.NEXT_PUBLIC_WEB_URL,
- ).toString(),
- width: 1200,
- height: 630,
- },
- ],
+ images: [{ url: ogImageUrl, width: 1200, height: 630 }],
},
robots: "noindex, nofollow",
}),
@@ -287,27 +286,13 @@ export async function generateMetadata(
title: "Cap: Password Protected Video",
description: "This video is password protected.",
openGraph: {
- images: [
- {
- url: new URL(
- `/api/video/og?videoId=${videoId}`,
- buildEnv.NEXT_PUBLIC_WEB_URL,
- ).toString(),
- width: 1200,
- height: 630,
- },
- ],
+ images: [{ url: ogImageUrl, width: 1200, height: 630 }],
},
twitter: {
card: "summary_large_image",
title: "Cap: Password Protected Video",
description: "This video is password protected.",
- images: [
- new URL(
- `/api/video/og?videoId=${videoId}`,
- buildEnv.NEXT_PUBLIC_WEB_URL,
- ).toString(),
- ],
+ images: [ogImageUrl],
},
robots: "noindex, nofollow",
}),
diff --git a/apps/web/lib/share-web-url.ts b/apps/web/lib/share-web-url.ts
new file mode 100644
index 000000000..d2df4ee67
--- /dev/null
+++ b/apps/web/lib/share-web-url.ts
@@ -0,0 +1,75 @@
+import { db } from "@cap/database";
+import { organizations } from "@cap/database/schema";
+import { buildEnv } from "@cap/env";
+import { eq } from "drizzle-orm";
+
+/**
+ * Hosts that always serve the default web URL, even when they do not match
+ * `NEXT_PUBLIC_WEB_URL` (preview deployments run on the same origins).
+ */
+const DEFAULT_HOSTNAMES = ["cap.so", "cap.link", "localhost", "127.0.0.1"];
+
+const normalizeHostname = (value: string | null | undefined) => {
+ const first = value?.split(",")[0]?.trim().toLowerCase();
+ if (!first) return "";
+ // Strip the port so `localhost:3000` still matches `localhost`.
+ return first.replace(/:\d+$/, "");
+};
+
+/** The hostname the visitor asked for, taken from the incoming request. */
+export const requestShareHostname = (headersList: Headers) =>
+ normalizeHostname(
+ headersList.get("x-forwarded-host") ?? headersList.get("host"),
+ );
+
+/**
+ * True when the request arrived on the default Cap origin, so share metadata
+ * can use `NEXT_PUBLIC_WEB_URL` without a database lookup.
+ */
+export const isDefaultShareHostname = (
+ hostname: string,
+ defaultWebUrl: string,
+) => {
+ if (!hostname) return true;
+ if (DEFAULT_HOSTNAMES.includes(hostname)) return true;
+ try {
+ return new URL(defaultWebUrl).hostname.toLowerCase() === hostname;
+ } catch {
+ return true;
+ }
+};
+
+/**
+ * The public origin that share metadata must advertise.
+ *
+ * A share page on a verified custom domain has to emit `og:url`, `og:image`,
+ * `og:video` and `canonical` on that same domain. Slack drops the preview
+ * image when those values point at another host, so a custom domain link
+ * unfurls as a bare title and description.
+ *
+ * `proxy.ts` already redirects unverified hosts away from `/s/`, so this
+ * lookup is a second check rather than the only one. It returns the default
+ * web URL whenever the host is unknown, unverified, or the query fails.
+ */
+export const resolveShareWebUrl = async (
+ headersList: Headers,
+): Promise<string> => {
+ const defaultWebUrl = buildEnv.NEXT_PUBLIC_WEB_URL;
+ const hostname = requestShareHostname(headersList);
+
+ if (isDefaultShareHostname(hostname, defaultWebUrl)) return defaultWebUrl;
+
+ try {
+ const [organization] = await db()
+ .select({ domainVerified: organizations.domainVerified })
+ .from(organizations)
+ .where(eq(organizations.customDomain, hostname))
+ .limit(1);
+
+ if (!organization?.domainVerified) return defaultWebUrl;
+ return `https://${hostname}`;
+ } catch (error) {
+ console.error("Failed to resolve custom domain for share metadata", error);
+ return defaultWebUrl;
+ }
+};