Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Reports: serve the public share page as static HTML with no app bundle (#628)
Ben Senescu892ed294b365
diff --git a/specs/0014-public-share-links.md b/specs/0014-public-share-links.mdindex 46bc34bd..a41dad7b 100644--- a/specs/0014-public-share-links.md+++ b/specs/0014-public-share-links.md@@ -15,7 +15,7 @@ Accepted. Shipped in PR #616 on top of reports (`specs/0012-dynamic-reports.md`)**Data.** Two columns on `reports`: `share_token` (nullable, unique) and `shared_at`. The token is 192 random bits as 32 base64url characters, stored as-is; it is a capability, and revoking it means nulling it. Sharing mints, unsharing nulls, and content saves never touch either column.-**Public page** at `/s/<token>`: no auth guard, server-rendered enough for link previews, with `noindex` and Open Graph tags from the title and the summary's first line. The summary is markdown and the preview does not try to render it: a stray `##` costs less than a stripper that eats the minus sign off a number.+**Public page** at `/s/<token>`: a hand-written HTML document the worker serves, not a route in the app, with no auth guard, `noindex`, and Open Graph tags from the title and the summary's first line. The bar, the frame and the preview tags are all in the first response, and the page ships no JavaScript beyond the Share button's clipboard handler. The reader is usually someone who has never opened OpenSEO, and the app's root shell renders only on the client, so a page inside it would have cost them the whole app bundle before the frame existed. The summary is markdown and the preview does not try to render it: a stray `##` costs less than a stripper that eats the minus sign off a number.**Raw endpoint** at `/s/<token>/raw` serves the stored HTML with the same sandbox policy as the in-app route, `frame-ancestors 'self'` and a noindex header. The raw document only renders inside the frame: a request whose fetch destination is not an iframe is redirected to the wrapped page, and a client that sends no destination header is served the document, since it cannot load the wrapper's frame either. A token of the wrong shape is answered before any query.@@ -42,6 +42,7 @@ Shares, unshares and public views are counted in telemetry, the last with a hash- An agent-facing share tool: sharing is a human decision made on the report page.- A per-organization cap and a rate limit: deferred until abuse shows up.- Edge caching: deferred out of the first PR, then added as the 60-second cache above once the query-string redirect closed the cache-key hole.+- A React route for the public page: shipped first and replaced once measured. The frame could not mount until the app bundle had loaded and hydrated, so a first-time reader waited on hundreds of kilobytes of JavaScript that a two-button bar does not need.## Not in scopediff --git a/src/lib/auth-redirect.test.ts b/src/lib/auth-redirect.test.tsindex d6d96cff..772a5118 100644--- a/src/lib/auth-redirect.test.ts+++ b/src/lib/auth-redirect.test.ts@@ -6,6 +6,7 @@ import {getOAuthSignedQuery,getSignInHref,getVerifyEmailSearch,+ isDocumentRoute,normalizeAuthRedirect,} from "./auth-redirect";@@ -23,6 +24,21 @@ const oauthSearch = new URLSearchParams({}).toString();describe("auth redirect helpers", () => {+ it("reloads report documents and public shares after sign-in", () => {+ const share = `/s/${"a".repeat(32)}`;+ for (const destination of [+ "/r/report-id",+ share,+ `${share}/`,+ `${share}?source=email#top`,+ `${share}/raw`,+ ]) {+ expect(isDocumentRoute(destination)).toBe(true);+ }+ expect(isDocumentRoute("/projects")).toBe(false);+ expect(isDocumentRoute("/sign-in")).toBe(false);+ });+it("defaults unsafe or missing redirects to the app root", () => {expect(normalizeAuthRedirect(undefined)).toBe("/");expect(normalizeAuthRedirect("https://evil.example/app")).toBe("/");diff --git a/src/lib/auth-redirect.ts b/src/lib/auth-redirect.tsindex 7908122d..cdaa9d19 100644--- a/src/lib/auth-redirect.ts+++ b/src/lib/auth-redirect.ts@@ -80,9 +80,8 @@ export function getCurrentAuthRedirectFromHref(href: string) {* one lands the user on a blank page. Navigate to these with a document load.*/export function isDocumentRoute(redirectTo: string) {- // Every componentless route the app can navigate to must reload; /r/ is the- // only one (/s/<token>/raw is never a router destination).- return redirectTo.startsWith("/r/");+ // Both member reports and public shares are served by document handlers.+ return redirectTo.startsWith("/r/") || redirectTo.startsWith("/s/");}export function getSignInSearch(redirectTo: string) {diff --git a/src/routes/s/$token/index.ts b/src/routes/s/$token/index.tsnew file mode 100644index 00000000..9364b50f--- /dev/null+++ b/src/routes/s/$token/index.ts@@ -0,0 +1,15 @@+import { createFileRoute } from "@tanstack/react-router";+import { renderSharePage } from "@/server/features/reports/sharePage";++// The public share page is a raw-Response route, like the two document routes:+// no React, no auth guard, no app bundle for a reader who has never signed in.+// No `component`, on purpose: one would pull the server-only renderer (and+// `cloudflare:workers` with it) into the client bundle, and the app never+// navigates here client-side — the share modal links to it with a plain anchor.+export const Route = createFileRoute("/s/$token/")({+ server: {+ handlers: {+ GET: ({ params, request }) => renderSharePage(params.token, request),+ },+ },+});diff --git a/src/routes/s/$token/index.tsx b/src/routes/s/$token/index.tsxdeleted file mode 100644index 423cb0b0..00000000--- a/src/routes/s/$token/index.tsx+++ /dev/null@@ -1,159 +0,0 @@-import { createFileRoute } from "@tanstack/react-router";-import { Share2 } from "lucide-react";-import { toast } from "sonner";-import { ReportViewer } from "@/client/features/reports/ReportViewer";-import { formatRelativeTime } from "@/client/lib/relative-time";-import { loadSharePage } from "@/server/features/reports/sharePage";--// The public face of a shared report: no sign-in, no app shell, no sidebar.-// The document itself is never served into this page's origin — it comes from-// /s/<token>/raw inside the same sandboxed frame the in-app viewer uses, and-// that endpoint bounces anyone who opens it top-level back here, so shared-// content always carries this chrome.--const MARKETING_URL = "https://openseo.so/?utm_source=shared_report";--// The share sheet on touch devices only; on desktop macOS anchors it to the-// window rather than the button, so the clipboard is used instead.-async function shareLink(title: string) {- const url = window.location.href;- const touch = window.matchMedia("(pointer: coarse)").matches;- if (touch && typeof navigator.share === "function") {- await navigator.share({ title, url }).catch(() => undefined);- return;- }- try {- await navigator.clipboard.writeText(url);- toast.success("Link copied");- } catch {- toast.error("Clipboard not available");- }-}--export const Route = createFileRoute("/s/$token/")({- loader: ({ params }) => loadSharePage(params.token),- // The loader is server-only (see sharePage.ts). Nothing on this page- // navigates or invalidates, and this makes sure of it.- shouldReload: false,- staleTime: Infinity,- head: ({ loaderData: data }) => {- if (!data) return {};- const title = `${data.title} · OpenSEO`;- return {- meta: [- { title },- // A shared report is a private link, not a page we want in an index.- // The raw endpoint sets X-Robots-Tag for the same reason.- { name: "robots", content: "noindex, nofollow" },- { property: "og:type", content: "article" },- { property: "og:site_name", content: "OpenSEO" },- { property: "og:title", content: data.title },- { name: "twitter:title", content: data.title },- ...(data.description- ? [- { property: "og:description", content: data.description },- { name: "description", content: data.description },- ]- : []),- { property: "og:url", content: data.url },- ...(data.state === "ok"- ? [- { property: "og:image", content: data.imageUrl },- { property: "og:image:width", content: "1200" },- { property: "og:image:height", content: "630" },- { property: "og:image:alt", content: `${data.title} · OpenSEO` },- { name: "twitter:image", content: data.imageUrl },- { name: "twitter:image:alt", content: `${data.title} · OpenSEO` },- { name: "twitter:card", content: "summary_large_image" },- ]- : []),- ],- };- },- component: SharedReportPage,-});--/** The two dead ends — a link that was never shared or was revoked, and an archived project. */-function SharedReportMessage({- heading,- detail,-}: {- heading: string;- detail: string;-}) {- return (- <div className="flex min-h-full flex-col items-center justify-center gap-3 px-6 text-center">- <h1 className="text-lg font-medium">{heading}</h1>- <p className="max-w-md text-sm text-base-content/60">{detail}</p>- <a- href={MARKETING_URL}- target="_blank"- rel="noreferrer"- className="btn btn-primary btn-sm"- >- Try OpenSEO- </a>- </div>- );-}--function SharedReportPage() {- const { token } = Route.useParams();- const data = Route.useLoaderData();-- if (data.state === "missing") {- return (- <SharedReportMessage- heading="This report isn't shared."- detail="The link may have been turned off, or the report may have been deleted."- />- );- }-- if (data.state === "archived") {- return (- <SharedReportMessage- heading="This project has been archived."- detail="Its reports are hidden until the owner restores it."- />- );- }-- return (- <div className="flex h-full flex-col bg-base-200">- <header className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 border-b border-base-300 bg-base-100 px-4 py-2">- {/* Full width below `sm` so the title owns its own row and the buttons- wrap under it instead of squeezing it to an ellipsis. */}- <div className="w-full min-w-0 sm:w-auto sm:flex-1">- <h1 className="truncate text-sm font-medium">{data.title}</h1>- <p className="text-xs text-base-content/50">- Made with OpenSEO · Updated {formatRelativeTime(data.updatedAt)}- </p>- </div>- <div className="flex shrink-0 items-center gap-2">- <button- type="button"- className="btn btn-ghost btn-sm gap-1.5"- onClick={() => void shareLink(data.title)}- >- <Share2 className="size-4" />- <span className="hidden sm:inline">Share</span>- </button>- <a- href={MARKETING_URL}- target="_blank"- rel="noreferrer"- className="btn btn-primary btn-sm"- >- Try OpenSEO- </a>- </div>- </header>- <ReportViewer- src={`/s/${token}/raw`}- title={data.title}- className="min-h-0 flex-1 border-0 bg-base-100"- />- </div>- );-}diff --git a/src/server/features/reports/sharePage.test.ts b/src/server/features/reports/sharePage.test.tsindex a2f6d219..e590d96a 100644--- a/src/server/features/reports/sharePage.test.ts+++ b/src/server/features/reports/sharePage.test.ts@@ -1,52 +1,81 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { loadSharePage } from "./sharePage";+import { load } from "cheerio";+import { renderSharePage } from "./sharePage";+import { REPORT_IFRAME_SANDBOX } from "@/shared/report-sandbox";const mocks = vi.hoisted(() => ({env: {AUTH_MODE: "hosted" as string | undefined,},getSharedReportByToken: vi.fn(),- setResponseStatus: vi.fn(),- setResponseHeader: vi.fn(),}));vi.mock("cloudflare:workers", () => ({ env: mocks.env }));-vi.mock("@tanstack/react-start/server", () => ({- getRequest: () => new Request("https://app.example.com/s/token"),- setResponseStatus: mocks.setResponseStatus,- setResponseHeader: mocks.setResponseHeader,-}));vi.mock("@/server/features/reports/repositories/ReportRepository", () => ({ReportRepository: { getSharedReportByToken: mocks.getSharedReportByToken },}));const TOKEN = "a".repeat(32);+const request = () => new Request(`https://app.example.com/s/${TOKEN}`);-// Only what the page reads off the row.+// Only what the page reads off the row. The title and summary carry the+// characters that must not reach the HTML unescaped.const SHARED_REPORT = {- title: "badseo.dev SEO audit",- summary: "\nFix the titles first.\n\nThen the meta descriptions.",+ title: "badseo.dev <SEO> audit",+ summary: '\nFix the "titles" first.\n\nThen the meta descriptions.',updatedAt: "2026-09-01T10:00:00.000Z",projectDomain: "badseo.dev",archived: false,};+async function renderedImageUrl(): Promise<string> {+ const response = await renderSharePage(TOKEN, request());+ return (+ load(await response.text())('meta[property="og:image"]').attr("content") ??+ ""+ );+}+beforeEach(() => {mocks.env.AUTH_MODE = "hosted";mocks.getSharedReportByToken.mockResolvedValue(SHARED_REPORT);});-describe("loadSharePage", () => {- it("returns the report's title, the summary's first line and the canonical url", async () => {- await expect(loadSharePage(TOKEN)).resolves.toEqual({- state: "ok",- title: "badseo.dev SEO audit",- description: "Fix the titles first.",- url: `https://app.example.com/s/${TOKEN}`,- imageUrl: `https://app.example.com/s/${TOKEN}/og.png?v=2026-09-01T10%3A00%3A00.000Z&domain=badseo.dev`,- updatedAt: "2026-09-01T10:00:00.000Z",- });- expect(mocks.setResponseStatus).not.toHaveBeenCalled();+describe("renderSharePage", () => {+ it("puts the framed document, the escaped title and the preview tags in the first response", async () => {+ const response = await renderSharePage(TOKEN, request());+ const html = await response.text();++ expect(response.status).toBe(200);+ expect(response.headers.get("content-type")).toBe(+ "text/html; charset=utf-8",+ );+ expect(response.headers.get("cache-control")).toBe("no-store");+ expect(html).toContain(+ `<iframe src="/s/${TOKEN}/raw" sandbox="${REPORT_IFRAME_SANDBOX}"`,+ );+ expect(html).toContain(+ "<title>badseo.dev <SEO> audit · OpenSEO</title>",+ );+ expect(html).toContain(+ '<meta property="og:description" content="Fix the "titles" first."/>',+ );+ expect(html).toContain(+ `<meta property="og:url" content="https://app.example.com/s/${TOKEN}"/>`,+ );+ expect(html).toContain('<meta name="robots" content="noindex, nofollow"/>');+ const $ = load(html);+ const imageUrl = `https://app.example.com/s/${TOKEN}/og.png?v=2026-09-01T10%3A00%3A00.000Z&domain=badseo.dev`;+ expect($('meta[property="og:image"]').attr("content")).toBe(imageUrl);+ expect($('meta[name="twitter:image"]').attr("content")).toBe(imageUrl);+ expect($('meta[property="og:image:alt"]').attr("content")).toBe(+ `${SHARED_REPORT.title} · OpenSEO`,+ );+ expect($('meta[name="twitter:image:alt"]').attr("content")).toBe(+ `${SHARED_REPORT.title} · OpenSEO`,+ );+ // No app bundle: the reader has never signed in and needs none of it.+ expect(html).not.toContain("/assets/");});it.each([@@ -60,37 +89,37 @@ describe("loadSharePage", () => {...SHARED_REPORT,projectDomain: before,});- const original = await loadSharePage(TOKEN);+ const original = await renderedImageUrl();mocks.getSharedReportByToken.mockResolvedValue({...SHARED_REPORT,projectDomain: after,});- const updated = await loadSharePage(TOKEN);- expect(updated.updatedAt).toBe(original.updatedAt);- expect(updated.imageUrl).not.toBe(original.imageUrl);- expect(new URL(updated.imageUrl).searchParams.get("domain")).toBe(- after ?? "",+ const updated = await renderedImageUrl();+ expect(new URL(updated).searchParams.get("v")).toBe(+ new URL(original).searchParams.get("v"),);+ expect(updated).not.toBe(original);+ expect(new URL(updated).searchParams.get("domain")).toBe(after ?? "");},);it("versions by the displayed hostname, not URL formatting", async () => {- const original = await loadSharePage(TOKEN);+ const original = await renderedImageUrl();mocks.getSharedReportByToken.mockResolvedValue({...SHARED_REPORT,projectDomain: "https://www.badseo.dev/path?query=value",});- expect((await loadSharePage(TOKEN)).imageUrl).toBe(original.imageUrl);+ expect(await renderedImageUrl()).toBe(original);});it("changes the image URL when a report is saved again", async () => {- const original = await loadSharePage(TOKEN);+ const original = await renderedImageUrl();mocks.getSharedReportByToken.mockResolvedValue({...SHARED_REPORT,title: "Updated audit",updatedAt: "2026-09-02T10:00:00.000Z",});- expect((await loadSharePage(TOKEN)).imageUrl).not.toBe(original.imageUrl);+ expect(await renderedImageUrl()).not.toBe(original);});// The reader is told the project is archived; the report's own title is@@ -101,16 +130,18 @@ describe("loadSharePage", () => {archived: true,});- await expect(loadSharePage(TOKEN)).resolves.toMatchObject({- state: "archived",- title: "Report unavailable",- imageUrl: "",- });- expect(mocks.setResponseStatus).toHaveBeenCalledWith(404);+ const response = await renderSharePage(TOKEN, request());+ const html = await response.text();++ expect(response.status).toBe(404);+ expect(html).toContain("This project has been archived.");+ expect(html).not.toContain("badseo.dev");+ expect(html).not.toContain("og:image");+ expect(html).not.toContain("twitter:image");});- // A revoked link, a guessed one and a switched-off kill switch are the same- // answer: a link that stopped working must not confirm it once did.+ // A revoked link and a guessed one are the same answer: a link that stopped+ // working must not confirm it once did.it.each([["an unknown or revoked token",@@ -124,20 +155,22 @@ describe("loadSharePage", () => {mocks.env.AUTH_MODE = "cloudflare_access";},],- ])("reports missing for %s", async (_case, arrange) => {+ ])("answers not shared for %s", async (_case, arrange) => {arrange();- await expect(loadSharePage(TOKEN)).resolves.toMatchObject({- state: "missing",- imageUrl: "",- });- expect(mocks.setResponseStatus).toHaveBeenCalledWith(404);+ const response = await renderSharePage(TOKEN, request());++ expect(response.status).toBe(404);+ const html = await response.text();+ expect(html).toContain("This report isn't shared.");+ expect(html).not.toContain("og:image");+ expect(html).not.toContain("twitter:image");});- it("reports missing for a malformed token without querying", async () => {- await expect(loadSharePage("nope")).resolves.toMatchObject({- state: "missing",- });+ it("answers a malformed token without querying", async () => {+ const response = await renderSharePage("nope", request());++ expect(response.status).toBe(404);expect(mocks.getSharedReportByToken).not.toHaveBeenCalled();});});diff --git a/src/server/features/reports/sharePage.ts b/src/server/features/reports/sharePage.tsdeleted file mode 100644index d37cc47b..00000000--- a/src/server/features/reports/sharePage.ts+++ /dev/null@@ -1,106 +0,0 @@-import { createServerOnlyFn } from "@tanstack/react-start";-import {- getRequest,- setResponseHeader,- setResponseStatus,-} from "@tanstack/react-start/server";-import { ReportRepository } from "@/server/features/reports/repositories/ReportRepository";-import {- SHARE_TOKEN_PATTERN,- sharesEnabled,-} from "@/server/features/reports/shareAccess";-import { sharePath } from "@/shared/report-share";-import { domainField } from "@/types/schemas/domain";--/** What `/s/<token>` renders, and all it is told. No report or project id. */-type SharePageData = {- state: "ok" | "archived" | "missing";- title: string;- /** Open Graph description: the summary's first line, or "" when there is none. */- description: string;- /** Absolute canonical URL, for og:url. */- url: string;- /** Absolute image URL, versioned by the saved report and displayed hostname. */- imageUrl: string;- /** When the report was last saved, for the bar's "Updated …". */- updatedAt: string;-};--const MAX_DESCRIPTION_CHARS = 200;--/**- * The link preview's description: the summary's first non-empty line, capped.- * The summary is markdown, and no attempt is made to render it — a stray `##`- * in a preview is a smaller problem than a stripper that eats a leading minus- * sign off a number.- */-function shareDescription(summary: string): string {- const line = summary- .split("\n")- .map((raw) => raw.trim())- .find((raw) => raw.length > 0);- if (!line) return "";- return line.length > MAX_DESCRIPTION_CHARS- ? `${line.slice(0, MAX_DESCRIPTION_CHARS - 1).trimEnd()}…`- : line;-}--/**- * The public page's loader. Server-only rather than a server function: every- * server function in this app runs ensureUserMiddleware, and this page has no- * user. `createServerOnlyFn` is the framework's marker for that — the body and- * its imports are compiled out of the client bundle. The route pins- * `shouldReload: false` so nothing ever calls it from the browser.- *- * An unknown token, an unshared report and a switched-off kill switch are all- * "missing": a shared link that was revoked must not confirm it once existed.- */-export const loadSharePage = createServerOnlyFn(- async (token: string): Promise<SharePageData> => {- const url = new URL(getRequest().url);- const canonical = `${url.origin}${sharePath(token)}`;- // Every dead end answers 404, so a crawler, a monitor or a browser's- // history sees a page that is not there rather than a 200 with an apology.- // The archived page keeps the generic title too: the reader is told the- // project is archived, and the report's own title is content the link no- // longer grants access to.- const unavailable = (state: "missing" | "archived"): SharePageData => {- setResponseStatus(404);- return {- state,- title: "Report unavailable",- description: "",- url: canonical,- imageUrl: "",- updatedAt: "",- };- };-- // The page carries the title and summary in its head, so a revoked link- // must not live on in an intermediary cache any longer than the document.- setResponseHeader("Cache-Control", "no-store");- if (!(await sharesEnabled())) return unavailable("missing");- if (!SHARE_TOKEN_PATTERN.test(token)) return unavailable("missing");-- const report = await ReportRepository.getSharedReportByToken(token);- if (!report) return unavailable("missing");- if (report.archived) return unavailable("archived");-- const domain = domainField.safeParse(report.projectDomain);- // These parameters only version the URL; the image route reads its content- // from the authorized report, never from query parameters.- const imageVersion = new URLSearchParams({- v: report.updatedAt,- domain: domain.success ? domain.data : "",- });-- return {- state: "ok",- title: report.title,- description: shareDescription(report.summary),- url: canonical,- imageUrl: `${canonical}/og.png?${imageVersion}`,- updatedAt: report.updatedAt,- };- },-);diff --git a/src/server/features/reports/sharePage.tsx b/src/server/features/reports/sharePage.tsxnew file mode 100644index 00000000..46808242--- /dev/null+++ b/src/server/features/reports/sharePage.tsx@@ -0,0 +1,260 @@+import { renderToStaticMarkup } from "react-dom/server";+import { formatRelativeTime } from "@/client/lib/relative-time";+import { ReportRepository } from "@/server/features/reports/repositories/ReportRepository";+import {+ SHARE_TOKEN_PATTERN,+ sharesEnabled,+} from "@/server/features/reports/shareAccess";+import { REPORT_IFRAME_SANDBOX } from "@/shared/report-sandbox";+import { sharePath } from "@/shared/report-share";+import { domainField } from "@/types/schemas/domain";++// The public face of a shared report, `/s/<token>`: a slim bar and the+// document in the same sandboxed frame the in-app viewer uses. Rendered to a+// static string on the server rather than served as a React route, because the+// reader is usually someone who has never opened OpenSEO: the app's root shell+// renders only on the client, so a route inside it cost them the whole app+// bundle (~400 KB gzipped) downloaded, parsed and hydrated before the frame+// even existed. This page puts the frame in the first response and ships no+// JavaScript beyond the Share button's clipboard handler. JSX so every value+// from the row is escaped by React, not by hand.++const MARKETING_URL = "https://openseo.so/?utm_source=shared_report";++const MAX_DESCRIPTION_CHARS = 200;++/**+ * The link preview's description: the summary's first non-empty line, capped.+ * The summary is markdown, and no attempt is made to render it — a stray `##`+ * in a preview is a smaller problem than a stripper that eats a leading minus+ * sign off a number.+ */+function shareDescription(summary: string): string {+ const line = summary+ .split("\n")+ .map((raw) => raw.trim())+ .find((raw) => raw.length > 0);+ if (!line) return "";+ return line.length > MAX_DESCRIPTION_CHARS+ ? `${line.slice(0, MAX_DESCRIPTION_CHARS - 1).trimEnd()}…`+ : line;+}++// The app's own light and dark palettes (app.css), so the bar matches the+// product without loading its stylesheet. Dark follows the OS: an anonymous+// reader has no stored preference.+const STYLES = `+:root{color-scheme:light dark;--bg:oklch(97% 0 0);--surface:oklch(100% 0 0);--border:oklch(92% 0 0);--text:oklch(20% 0 0);--muted:oklch(20% 0 0 / .5);--primary:oklch(50% 0.12 262);--primary-text:oklch(100% 0 0);--ghost-hover:oklch(20% 0 0 / .08)}+@media (prefers-color-scheme:dark){:root{--bg:oklch(12% 0 0);--surface:oklch(18% 0 0);--border:oklch(27% 0 0);--text:oklch(92% 0 0);--muted:oklch(92% 0 0 / .5);--primary:oklch(66% 0.12 262);--ghost-hover:oklch(92% 0 0 / .1)}}+*{box-sizing:border-box}+html,body{height:100%;margin:0}+body{display:flex;flex-direction:column;background:var(--bg);color:var(--text);font:14px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}+header{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:8px 16px;padding:8px 16px;background:var(--surface);border-bottom:1px solid var(--border)}+.title{width:100%;min-width:0}+@media (min-width:640px){.title{width:auto;flex:1}}+h1{margin:0;font-size:14px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.meta{margin:0;font-size:12px;color:var(--muted)}+.actions{display:flex;flex-shrink:0;align-items:center;gap:8px}+.btn{display:inline-flex;align-items:center;gap:6px;height:32px;padding:0 12px;border:1px solid transparent;border-radius:6px;font:inherit;font-weight:600;color:inherit;background:transparent;cursor:pointer;text-decoration:none}+.btn:hover{background:var(--ghost-hover)}+.btn.primary{background:var(--primary);border-color:var(--primary);color:var(--primary-text)}+.btn.primary:hover{filter:brightness(.92)}+.btn svg{width:16px;height:16px}+iframe{flex:1;min-height:0;width:100%;border:0;background:var(--surface)}+main{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:24px;text-align:center}+main h1{white-space:normal;font-size:18px}+main p{max-width:28rem;margin:0;color:var(--muted)}+`;++// Share sheet on touch devices; the clipboard elsewhere (desktop macOS anchors+// the sheet to the window, not the button). The label is the feedback.+const SHARE_SCRIPT = `+document.getElementById("share").addEventListener("click",async function(){+ var url=location.href,label=this.querySelector("span");+ if(matchMedia("(pointer: coarse)").matches&&navigator.share){+ try{await navigator.share({title:document.title,url:url})}catch(e){}+ return;+ }+ try{await navigator.clipboard.writeText(url);label.textContent="Link copied"}+ catch(e){label.textContent="Copy failed"}+ setTimeout(function(){label.textContent="Share"},2000);+});`;++function TryButton() {+ return (+ <a+ className="btn primary"+ href={MARKETING_URL}+ target="_blank"+ rel="noreferrer"+ >+ Try OpenSEO+ </a>+ );+}++function Document({+ title,+ head,+ children,+}: {+ title: string;+ head?: React.ReactNode;+ children: React.ReactNode;+}) {+ return (+ <html lang="en">+ <head>+ <meta charSet="utf-8" />+ <meta+ name="viewport"+ content="width=device-width, initial-scale=1, viewport-fit=cover"+ />+ <meta name="robots" content="noindex, nofollow" />+ <title>{`${title} · OpenSEO`}</title>+ {head}+ <link rel="icon" href="/favicon.ico" />+ <style dangerouslySetInnerHTML={{ __html: STYLES }} />+ </head>+ <body>{children}</body>+ </html>+ );+}++function htmlResponse(page: React.ReactElement, status: number): Response {+ return new Response(`<!doctype html>${renderToStaticMarkup(page)}`, {+ status,+ headers: {+ "Content-Type": "text/html; charset=utf-8",+ // The page carries the title and summary in its head, so a revoked link+ // must not live on in an intermediary cache any longer than the document.+ "Cache-Control": "no-store",+ },+ });+}++/** The two dead ends — a link that was never shared or was revoked, and an archived project. */+function unavailable(heading: string, detail: string): Response {+ // Every dead end answers 404, so a crawler, a monitor or a browser's history+ // sees a page that is not there rather than a 200 with an apology. The+ // generic title keeps the report's own title out of it: that is content the+ // link no longer grants access to.+ return htmlResponse(+ <Document title="Report unavailable">+ <main>+ <h1>{heading}</h1>+ <p>{detail}</p>+ <TryButton />+ </main>+ </Document>,+ 404,+ );+}++const missing = () =>+ unavailable(+ "This report isn't shared.",+ "The link may have been turned off, or the report may have been deleted.",+ );++/**+ * The public page. Reads the same row the raw endpoint reads and puts the frame+ * pointing at `/s/<token>/raw` straight into the HTML, so the browser requests+ * the document as soon as it has parsed the head.+ */+export async function renderSharePage(+ token: string,+ request: Request,+): Promise<Response> {+ if (!(await sharesEnabled())) return missing();+ if (!SHARE_TOKEN_PATTERN.test(token)) return missing();++ const report = await ReportRepository.getSharedReportByToken(token);+ if (!report) return missing();+ if (report.archived) {+ return unavailable(+ "This project has been archived.",+ "Its reports are hidden until the owner restores it.",+ );+ }++ const description = shareDescription(report.summary);+ const canonical = `${new URL(request.url).origin}${sharePath(token)}`;+ const domain = domainField.safeParse(report.projectDomain);+ // These parameters only version the URL; the image route reads its content+ // from the authorized report, never from query parameters.+ const imageVersion = new URLSearchParams({+ v: report.updatedAt,+ domain: domain.success ? domain.data : "",+ });+ const imageUrl = `${canonical}/og.png?${imageVersion}`;++ return htmlResponse(+ <Document+ title={report.title}+ head={+ <>+ <meta property="og:type" content="article" />+ <meta property="og:site_name" content="OpenSEO" />+ <meta property="og:title" content={report.title} />+ <meta name="twitter:title" content={report.title} />+ {description ? (+ <>+ <meta property="og:description" content={description} />+ <meta name="description" content={description} />+ </>+ ) : null}+ <meta property="og:url" content={canonical} />+ <meta property="og:image" content={imageUrl} />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta property="og:image:alt" content={`${report.title} · OpenSEO`} />+ <meta name="twitter:image" content={imageUrl} />+ <meta+ name="twitter:image:alt"+ content={`${report.title} · OpenSEO`}+ />+ <meta name="twitter:card" content="summary_large_image" />+ </>+ }+ >+ <header>+ <div className="title">+ <h1>{report.title}</h1>+ <p className="meta">+ Made with OpenSEO · Updated {formatRelativeTime(report.updatedAt)}+ </p>+ </div>+ <div className="actions">+ <button type="button" className="btn" id="share">+ <svg+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden="true"+ >+ <circle cx="18" cy="5" r="3" />+ <circle cx="6" cy="12" r="3" />+ <circle cx="18" cy="19" r="3" />+ <line x1="8.59" x2="15.42" y1="13.51" y2="17.49" />+ <line x1="15.41" x2="8.59" y1="6.51" y2="10.49" />+ </svg>+ <span>Share</span>+ </button>+ <TryButton />+ </div>+ </header>+ <iframe+ src={`${sharePath(token)}/raw`}+ sandbox={REPORT_IFRAME_SANDBOX}+ referrerPolicy="no-referrer"+ title={report.title}+ />+ <script dangerouslySetInnerHTML={{ __html: SHARE_SCRIPT }} />+ </Document>,+ 200,+ );+}