Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
feat(reports): public share links (#616)
Ben Senescu2d404f5237ad
diff --git a/alchemy.run.ts b/alchemy.run.tsindex 9ae6192d..1b107d6a 100644--- a/alchemy.run.ts+++ b/alchemy.run.ts@@ -276,6 +276,7 @@ const dataEnv = {AUTUMN_WEBHOOK_SECRET: optionalSecret("AUTUMN_WEBHOOK_SECRET"),DUB_API_KEY: optionalSecret("DUB_API_KEY"),GDPR_ERASURE_SECRET: optionalSecret("GDPR_ERASURE_SECRET"),+ SHARES_ENABLED: optionalVar("SHARES_ENABLED"),LOOPS_API_KEY: optionalSecret("LOOPS_API_KEY"),LOOPS_TRANSACTIONAL_VERIFY_EMAIL_ID: optionalVar("LOOPS_TRANSACTIONAL_VERIFY_EMAIL_ID",diff --git a/runbooks/gdpr-erasure.md b/runbooks/gdpr-erasure.mdindex c043fecb..871982e1 100644--- a/runbooks/gdpr-erasure.md+++ b/runbooks/gdpr-erasure.md@@ -78,12 +78,13 @@ The execution order is designed for safe retries:3. Delete the organizations and user in one Postgres transaction, relying onforeign-key cascades for project data, then verify the root rows are gone.-Two classes are re-attributed rather than deleted, because they have no user-foreign key and a surviving multi-member organization keeps them: `reports` and-`report_templates` (both `created_by_user_id` becomes `gdpr-deleted-user`). The-dry run counts them as `attributed_reports` and `attributed_report_templates`,-alongside the `reports` and `report_templates` in the target's projects — those-cascade away with the project when its organization is deleted.+Reports and report templates have no user foreign key, so step 3 re-attributes+them rather than deleting them: `created_by_user_id` becomes+`gdpr-deleted-user`, share links on the user's reports are revoked in the same+statement, and a surviving multi-member organization keeps the rows. The dry run+counts them as `attributed_reports` and `attributed_report_templates`, alongside+the `reports` and `report_templates` in the target's own projects, which cascade+away with the project when its organization is deleted.If a step fails, fix the reported credential or service error and run the samecommand again. Vendor absence and already-finished Workflows are treated as@@ -98,6 +99,11 @@ configured retention. Database backups and billing records that must be keptfor tax, fraud, or legal obligations should be isolated from production accessand allowed to expire under the documented retention schedule.+Reports the erased user created survive in a multi-member organization with+their attribution wiped, and the same statement revokes any public share link+on those reports, so `/s/<token>` stops resolving. A link another member opened+on a report they created is untouched.+Prompt-response cache objects written after this erasure tooling was deployedcarry an organization tag and are deleted by the command. Older untagged cacheobjects cannot be attributed to a user from their hashed key; they remaindiff --git a/scripts/erase-user-data.ts b/scripts/erase-user-data.tsindex 343acbe3..6c99219b 100644--- a/scripts/erase-user-data.ts+++ b/scripts/erase-user-data.ts@@ -302,6 +302,13 @@ async function buildInventory(db: Db, user: UserRow) {schema.reportTemplates,eq(schema.reportTemplates.createdByUserId, user.id),),+ shared_reports: await db.$count(+ schema.reports,+ and(+ eq(schema.reports.createdByUserId, user.id),+ isNotNull(schema.reports.shareToken),+ ),+ ),gsc_connections: await db.$count(schema.gscConnections,eq(schema.gscConnections.connectedByUserId, user.id),@@ -505,9 +512,16 @@ async function erasePostgres(db: Db, user: UserRow, organizationIds: string[]) {.where(eq(schema.audits.startedByUserId, user.id));// reports.created_by_user_id has no FK either (same reason as audits), so a// surviving multi-member org keeps its reports with the attribution wiped.+ // Any public link on a report they created is revoked in the same+ // statement: the link is a capability published from their work, and it+ // must not outlive them.await tx.update(schema.reports)- .set({ createdByUserId: "gdpr-deleted-user" })+ .set({+ createdByUserId: "gdpr-deleted-user",+ shareToken: null,+ sharedAt: null,+ }).where(eq(schema.reports.createdByUserId, user.id));await tx.update(schema.reportTemplates)diff --git a/specs/0014-public-share-links.md b/specs/0014-public-share-links.mdnew file mode 100644index 00000000..2afca930--- /dev/null+++ b/specs/0014-public-share-links.md@@ -0,0 +1,52 @@+# Public share links for reports++## Status++Accepted. Shipped in PR #616 on top of reports (`specs/0012-dynamic-reports.md`); the edge cache followed in PR #620.++## What it does++- A report gets a Share button with a "Public link" toggle. On, anyone with the link can open the report without signing in. Off, the link stops working. Sharing again mints a new link, so an old one never comes back.+- The link always shows the latest saved version and is hidden from search engines.+- The public page lives on the app domain and looks like a shared document: a slim bar with the title, "Made with OpenSEO", a Share button and a "Try OpenSEO" button, with the report filling the rest of the screen in the same sandboxed frame the in-app viewer uses.+- Sharing is hosted-only. A self-hosted deployment sits behind Cloudflare Access or has no auth at all, and neither can serve a link to a reader who is not signed in, so the Share button is not rendered and the server refuses the mint.++## How it works++**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.++**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.++**Edge cache.** The raw response is cacheable at the edge for 60 seconds and never in the browser, so revoking a link stops new readers within a minute. A request carrying a query string is redirected to the bare path before any lookup, so the cache key cannot be varied.++**States.** Unknown, unshared or deleted: one "not shared" page with a 404 status, so tokens cannot be probed. Archived project: 404 with the archived message; restoring the project brings the link back.++**One gate.** The mint, the public page and the raw endpoint ask the same question — hosted, and not switched off — so they cannot disagree. The kill switch is one environment variable that turns every public link off without a deploy; it fails open, so sharing is on unless the value is exactly "false", because an unset or misspelled value must not silently break every live link. A refusal is an ordinary validation error: the operator flipped the switch, and the reader does not need a bespoke code for it.++**Sandbox facts**, checked in the three major engines: meta refresh, `javascript:` and `data:` navigations, form submission and a `<meta>` policy that adds scripts are all refused, and the origin is opaque. A clicked link only replaces the frame's content; links that open a new tab do so with the opener severed.++Shares, unshares and public views are counted in telemetry, the last with a hashed token and the user agent so link-preview bots can be excluded. Erasing a user revokes the links on the reports they created; deleting a report or project kills the link by cascade.++## Alternatives considered++- An `is_public` boolean instead of a token: the URL would be the report id, so an old link would resurrect on re-share.+- Signed URLs: expiry and signing keys for links meant to stay live until revoked, and revocation would still need a database read.+- A separate shares table: a report has at most one public link, so a table adds a join for nothing.+- Raw HTML at top level on the app hostname: one abusive account could get the hostname flagged. Wrapping every shared document in our chrome is what makes the app domain the right place.+- A separate registrable domain: overkill once the document is wrapped in our chrome.+- Sharing under the no-auth self-host mode, with a dedicated error code explaining the Cloudflare Access refusal: one hosted-only check reads better than two modes and an error code that existed for one sentence.+- ETag revalidation: a revalidation answered before the token lookup would make revocation advisory.+- Print on the public page: a cancelled print dialog leaves a bare report open top-level on the app domain. Members print from the app.+- 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.++## Not in scope++An agent-facing share tool, a per-organization cap, rate limiting, an abuse-report link, view counts in the app, per-report preview images, embedding on third-party sites, passwords or expiry on links, indexable reports, a separate share domain.++## Later++Interactive reports are the one flip spec 0012 describes: `allow-scripts` without `allow-same-origin`, so a chart can run but has no cookies, storage or network. It is a one-way door: reports saved with scripts stop working if it is turned off again.diff --git a/src/client/features/projects/project-context/shared.tsx b/src/client/features/projects/project-context/shared.tsxindex 11b9214c..32f8db3a 100644--- a/src/client/features/projects/project-context/shared.tsx+++ b/src/client/features/projects/project-context/shared.tsx@@ -1,3 +1,4 @@+import { formatRelativeTime } from "@/client/lib/relative-time";import { useState, type ReactNode } from "react";import { useMutation, useQueryClient } from "@tanstack/react-query";import { Trash2 } from "lucide-react";@@ -63,20 +64,6 @@ export function Provenance({ by, at }: { by: ContextAuthor; at?: string }) {);}-function formatRelativeTime(iso: string): string {- const timestamp = new Date(iso).getTime();- if (Number.isNaN(timestamp)) return "recently";-- const minutes = Math.floor((Date.now() - timestamp) / 60_000);- if (minutes < 1) return "just now";- if (minutes < 60) return `${minutes}m ago`;- const hours = Math.floor(minutes / 60);- if (hours < 24) return `${hours}h ago`;- const days = Math.floor(hours / 24);- if (days < 30) return `${days}d ago`;- return new Date(timestamp).toLocaleDateString();-}-export function SectionHeader({title,hint,diff --git a/src/client/features/reports/ReportTemplatesList.tsx b/src/client/features/reports/ReportTemplatesList.tsxindex dfc28355..5bb360b9 100644--- a/src/client/features/reports/ReportTemplatesList.tsx+++ b/src/client/features/reports/ReportTemplatesList.tsx@@ -1,6 +1,6 @@import { Pencil, Trash2 } from "lucide-react";import { PortalMenu } from "@/client/components/PortalMenu";-import { formatRelativeTime } from "@/client/features/reports/shared";+import { formatRelativeTime } from "@/client/lib/relative-time";import type { ReportTemplate } from "@/types/schemas/report-templates";export function ReportTemplatesList({diff --git a/src/client/features/reports/ReportViewer.tsx b/src/client/features/reports/ReportViewer.tsxindex c3f00695..097a1d52 100644--- a/src/client/features/reports/ReportViewer.tsx+++ b/src/client/features/reports/ReportViewer.tsx@@ -1,10 +1,15 @@import { REPORT_IFRAME_SANDBOX } from "@/shared/report-sandbox";/**- * The only place the app renders model-written HTML. Everything that keeps it- * safe is the `sandbox` attribute plus the CSP the document response sets; the- * token list is shared with that header so a link behaves the same framed and- * top-level, and `allow-same-origin` is never added.+ * The only place the app renders model-written HTML, in the app and on the+ * public share page. Everything that keeps it safe is the `sandbox` attribute+ * plus the CSP the document response sets; the token list is shared with that+ * header so a link behaves the same framed and top-level, and+ * `allow-same-origin` is never added.+ *+ * Framed, the document is served byte for byte — the app injects nothing here.+ * The only injection is the print script on `?print=1`, which this viewer+ * never requests.*/export function ReportViewer({src,diff --git a/src/client/features/reports/ReportsList.tsx b/src/client/features/reports/ReportsList.tsxindex 9b0b0ee3..8f68a1e5 100644--- a/src/client/features/reports/ReportsList.tsx+++ b/src/client/features/reports/ReportsList.tsx@@ -1,10 +1,8 @@import { Link } from "@tanstack/react-router";import { Trash2 } from "lucide-react";import { PortalMenu } from "@/client/components/PortalMenu";-import {- formatCreatedBy,- formatRelativeTime,-} from "@/client/features/reports/shared";+import { formatCreatedBy } from "@/client/features/reports/shared";+import { formatRelativeTime } from "@/client/lib/relative-time";import type { ReportListItem } from "@/serverFunctions/reports";import { REPORT_APP_LIST_LIMIT } from "@/types/schemas/reports";diff --git a/src/client/features/reports/shared.tsx b/src/client/features/reports/shared.tsxindex 1dc9fb45..0cd3992f 100644--- a/src/client/features/reports/shared.tsx+++ b/src/client/features/reports/shared.tsx@@ -1,9 +1,18 @@+import { formatRelativeTime } from "@/client/lib/relative-time";import { useMutation, useQueryClient } from "@tanstack/react-query";+import { Copy, ExternalLink, X } from "lucide-react";import { toast } from "sonner";import { ConfirmDeleteModal } from "@/client/components/ConfirmDeleteModal";+import { Modal } from "@/client/components/Modal";import { getStandardErrorMessage } from "@/client/lib/error-messages";import { captureClientEvent } from "@/client/lib/posthog";-import { deleteReport, type ReportListItem } from "@/serverFunctions/reports";+import {+ deleteReport,+ shareReport,+ unshareReport,+ type ReportListItem,+} from "@/serverFunctions/reports";+import { sharePath } from "@/shared/report-share";// Query keys for both reports pages. staleTime is 0 wherever these are used:// the pages exist to inspect what an agent just wrote, so the app-wide@@ -14,27 +23,6 @@ export const reportsQueryKey = (projectId: string) =>export const reportQueryKey = (projectId: string, reportId: string) =>["report", projectId, reportId] as const;-const RELATIVE_UNITS: [Intl.RelativeTimeFormatUnit, number][] = [- ["year", 365 * 24 * 60 * 60 * 1000],- ["month", 30 * 24 * 60 * 60 * 1000],- ["day", 24 * 60 * 60 * 1000],- ["hour", 60 * 60 * 1000],- ["minute", 60 * 1000],-];--/** "3 hours ago" for an ISO timestamp; "just now" under a minute. */-export function formatRelativeTime(iso: string): string {- const then = new Date(iso).getTime();- if (Number.isNaN(then)) return "";- const diff = then - Date.now();- const absolute = Math.abs(diff);- const formatter = new Intl.RelativeTimeFormat("en-US", { numeric: "auto" });- for (const [unit, ms] of RELATIVE_UNITS) {- if (absolute >= ms) return formatter.format(Math.round(diff / ms), unit);- }- return "just now";-}-/*** "Ben · Claude Code". The person is the half that means something (it comes* from the session); the client half is a self-reported hint, so it stands@@ -102,3 +90,156 @@ export function DeleteReportModal({/>);}++/**+ * The share toggle. The link is built from the browser's own origin, so the+ * same report shares correctly from app.openseo.so and from a self-hosted+ * hostname without the server knowing either.+ */+export function ShareReportModal({+ report,+ onClose,+}: {+ report: Pick<+ ReportListItem,+ "id" | "projectId" | "title" | "shareToken" | "sharedAt"+ >;+ onClose: () => void;+}) {+ const queryClient = useQueryClient();+ const { projectId, id: reportId } = report;+ // Share and unshare in one mutation, keyed by the state the toggle is moving+ // to. The response is written straight into the report query so the modal+ // shows the new link without waiting for a refetch; the list is invalidated+ // because its rows carry the same metadata.+ const mutation = useMutation({+ mutationFn: (shared: boolean) =>+ shared+ ? shareReport({ data: { projectId, reportId } })+ : unshareReport({ data: { projectId, reportId } }),+ onSuccess: (result) => {+ // No client event here: the service already captures report:shared and+ // report:unshared server-side, and a second one would double the count.+ queryClient.setQueryData(+ reportQueryKey(projectId, reportId),+ (previous: ReportListItem | undefined) =>+ previous ? { ...previous, ...result } : previous,+ );+ void queryClient.invalidateQueries({+ queryKey: reportsQueryKey(projectId),+ });+ },+ });+ // The toggle follows the click while the mutation is in flight — a round+ // trip that leaves the switch sitting in its old position reads as broken.+ const shared = Boolean(report.shareToken);+ const url = report.shareToken+ ? `${window.location.origin}${sharePath(report.shareToken)}`+ : "";++ const copy = async () => {+ try {+ await navigator.clipboard.writeText(url);+ toast.success("Link copied");+ } catch {+ toast.error("Clipboard not available");+ }+ };++ return (+ <Modal+ onClose={onClose}+ labelledBy="share-report-title"+ maxWidth="max-w-lg"+ >+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <h3 id="share-report-title" className="text-base font-semibold">+ Share+ </h3>+ <p className="truncate text-sm text-base-content/60">+ {report.title}+ </p>+ </div>+ <button+ type="button"+ className="btn btn-ghost btn-sm btn-square -mr-2 -mt-1"+ aria-label="Close"+ onClick={onClose}+ >+ <X className="size-4" />+ </button>+ </div>++ <div className="rounded-lg border border-base-300">+ <label className="flex cursor-pointer items-center justify-between gap-4 p-4">+ <span className="min-w-0">+ <span className="block text-sm font-medium">Public link</span>+ <span className="block text-xs text-base-content/60">+ {shared+ ? "Anyone with the link can view. No sign-in needed."+ : "Only members of your organization can open it."}+ </span>+ </span>+ <input+ type="checkbox"+ className="toggle toggle-primary"+ checked={mutation.isPending ? mutation.variables : shared}+ disabled={mutation.isPending}+ onChange={(event) => mutation.mutate(event.target.checked)}+ />+ </label>++ {shared ? (+ <div className="space-y-3 border-t border-base-300 p-4">+ {/* The field wraps onto its own line when the row gets narrow, so+ the link stays readable on a phone instead of shrinking. */}+ <div className="flex flex-wrap items-stretch gap-2">+ <input+ readOnly+ value={url}+ aria-label="Share link"+ onFocus={(event) => event.target.select()}+ className="input input-sm input-bordered min-w-0 flex-1 basis-64 text-sm"+ />+ <div className="ml-auto flex items-stretch">+ <a+ href={url}+ target="_blank"+ rel="noreferrer"+ aria-label="Open link"+ title="Open"+ className="btn btn-sm btn-ghost rounded-r-none border border-r-0 border-base-300"+ >+ <ExternalLink className="size-4" />+ </a>+ <button+ type="button"+ onClick={() => void copy()}+ className="btn btn-sm btn-primary rounded-l-none"+ >+ <Copy className="size-4" />+ Copy link+ </button>+ </div>+ </div>+ <p className="text-xs text-base-content/50">+ Shows the latest saved version. Hidden from search engines.+ {report.sharedAt+ ? ` Link created ${formatRelativeTime(report.sharedAt)}.`+ : ""}+ </p>+ </div>+ ) : null}+ </div>++ {/* Shown in place rather than as a toast: the message belongs next to+ the toggle that would not move. */}+ {mutation.isError ? (+ <p className="text-sm text-error">+ {getStandardErrorMessage(mutation.error, "Failed to update sharing")}+ </p>+ ) : null}+ </Modal>+ );+}diff --git a/src/client/lib/relative-time.ts b/src/client/lib/relative-time.tsnew file mode 100644index 00000000..1c070620--- /dev/null+++ b/src/client/lib/relative-time.ts@@ -0,0 +1,20 @@+const RELATIVE_UNITS: [Intl.RelativeTimeFormatUnit, number][] = [+ ["year", 365 * 24 * 60 * 60 * 1000],+ ["month", 30 * 24 * 60 * 60 * 1000],+ ["day", 24 * 60 * 60 * 1000],+ ["hour", 60 * 60 * 1000],+ ["minute", 60 * 1000],+];++/** "3 hours ago" for an ISO timestamp; "just now" under a minute. */+export function formatRelativeTime(iso: string): string {+ const then = new Date(iso).getTime();+ if (Number.isNaN(then)) return "";+ const diff = then - Date.now();+ const absolute = Math.abs(diff);+ const formatter = new Intl.RelativeTimeFormat("en-US", { numeric: "auto" });+ for (const [unit, ms] of RELATIVE_UNITS) {+ if (absolute >= ms) return formatter.format(Math.round(diff / ms), unit);+ }+ return "just now";+}diff --git a/src/env.d.ts b/src/env.d.tsindex 8816c0bf..c2a630c3 100644--- a/src/env.d.ts+++ b/src/env.d.ts@@ -47,6 +47,13 @@ declare namespace Cloudflare {// HMAC secret for the operator-only GDPR storage-erasure endpoint.GDPR_ERASURE_SECRET?: string;+ // Kill switch for public report share links. Sharing is on unless this is+ // exactly "false", which turns off every live /s/<token> link and refuses+ // new ones — an incident lever that needs no code change. Alchemy+ // reconciles worker vars on every deploy, so a lasting value belongs in+ // the env file; a dashboard edit holds until the next deploy.+ SHARES_ENABLED?: string;+// Cloudflare Turnstile — signup captcha (hosted only). Secret verifies// tokens server-side; site key is public and inlined into the client build.TURNSTILE_SECRET_KEY?: string;diff --git a/src/lib/auth-redirect.ts b/src/lib/auth-redirect.tsindex f1e83dd4..7908122d 100644--- a/src/lib/auth-redirect.ts+++ b/src/lib/auth-redirect.ts@@ -80,7 +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 server-handler route must reload; /r/ is the only one.+ // 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/");}diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.tsindex 0e6f565a..fd5314f5 100644--- a/src/routeTree.gen.ts+++ b/src/routeTree.gen.ts@@ -33,8 +33,10 @@ import { Route as AppProjectsRouteImport } from './routes/_app/projects'import { Route as AppBillingRouteImport } from './routes/_app/billing'import { Route as AppAiRouteImport } from './routes/_app/ai'import { Route as Char91DotwellKnownChar93OpenaiAppsChallengeRouteImport } from './routes/[.well-known]/openai-apps-challenge'+import { Route as STokenIndexRouteImport } from './routes/s/$token/index'import { Route as AuthenticatedOnboardingIndexRouteImport } from './routes/_authenticated.onboarding.index'import { Route as AppSettingsIndexRouteImport } from './routes/_app/settings/index'+import { Route as STokenRawRouteImport } from './routes/s/$token/raw'import { Route as ApiAutumnSplatRouteImport } from './routes/api/autumn/$'import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$'import { Route as AppSettingsOrganizationRouteImport } from './routes/_app/settings/organization'@@ -185,6 +187,11 @@ const Char91DotwellKnownChar93OpenaiAppsChallengeRoute =path: '/.well-known/openai-apps-challenge',getParentRoute: () => rootRouteImport,} as any)+const STokenIndexRoute = STokenIndexRouteImport.update({+ id: '/s/$token/',+ path: '/s/$token/',+ getParentRoute: () => rootRouteImport,+} as any)const AuthenticatedOnboardingIndexRoute =AuthenticatedOnboardingIndexRouteImport.update({id: '/onboarding/',@@ -196,6 +203,11 @@ const AppSettingsIndexRoute = AppSettingsIndexRouteImport.update({path: '/',getParentRoute: () => AppSettingsRoute,} as any)+const STokenRawRoute = STokenRawRouteImport.update({+ id: '/s/$token/raw',+ path: '/s/$token/raw',+ getParentRoute: () => rootRouteImport,+} as any)const ApiAutumnSplatRoute = ApiAutumnSplatRouteImport.update({id: '/api/autumn/$',path: '/api/autumn/$',@@ -397,8 +409,10 @@ export interface FileRoutesByFullPath {'/settings/organization': typeof AppSettingsOrganizationRoute'/api/auth/$': typeof ApiAuthSplatRoute'/api/autumn/$': typeof ApiAutumnSplatRoute+ '/s/$token/raw': typeof STokenRawRoute'/settings/': typeof AppSettingsIndexRoute'/onboarding/': typeof AuthenticatedOnboardingIndexRoute+ '/s/$token/': typeof STokenIndexRoute'/p/$projectId/audit': typeof ProjectPProjectIdAuditRouteWithChildren'/p/$projectId/backlinks': typeof ProjectPProjectIdBacklinksRoute'/p/$projectId/brand-lookup': typeof ProjectPProjectIdBrandLookupRoute@@ -450,8 +464,10 @@ export interface FileRoutesByTo {'/settings/organization': typeof AppSettingsOrganizationRoute'/api/auth/$': typeof ApiAuthSplatRoute'/api/autumn/$': typeof ApiAutumnSplatRoute+ '/s/$token/raw': typeof STokenRawRoute'/settings': typeof AppSettingsIndexRoute'/onboarding': typeof AuthenticatedOnboardingIndexRoute+ '/s/$token': typeof STokenIndexRoute'/p/$projectId/backlinks': typeof ProjectPProjectIdBacklinksRoute'/p/$projectId/brand-lookup': typeof ProjectPProjectIdBrandLookupRoute'/p/$projectId/context': typeof ProjectPProjectIdContextRoute@@ -507,8 +523,10 @@ export interface FileRoutesById {'/_app/settings/organization': typeof AppSettingsOrganizationRoute'/api/auth/$': typeof ApiAuthSplatRoute'/api/autumn/$': typeof ApiAutumnSplatRoute+ '/s/$token/raw': typeof STokenRawRoute'/_app/settings/': typeof AppSettingsIndexRoute'/_authenticated/onboarding/': typeof AuthenticatedOnboardingIndexRoute+ '/s/$token/': typeof STokenIndexRoute'/_project/p/$projectId/audit': typeof ProjectPProjectIdAuditRouteWithChildren'/_project/p/$projectId/backlinks': typeof ProjectPProjectIdBacklinksRoute'/_project/p/$projectId/brand-lookup': typeof ProjectPProjectIdBrandLookupRoute@@ -564,8 +582,10 @@ export interface FileRouteTypes {| '/settings/organization'| '/api/auth/$'| '/api/autumn/$'+ | '/s/$token/raw'| '/settings/'| '/onboarding/'+ | '/s/$token/'| '/p/$projectId/audit'| '/p/$projectId/backlinks'| '/p/$projectId/brand-lookup'@@ -617,8 +637,10 @@ export interface FileRouteTypes {| '/settings/organization'| '/api/auth/$'| '/api/autumn/$'+ | '/s/$token/raw'| '/settings'| '/onboarding'+ | '/s/$token'| '/p/$projectId/backlinks'| '/p/$projectId/brand-lookup'| '/p/$projectId/context'@@ -673,8 +695,10 @@ export interface FileRouteTypes {| '/_app/settings/organization'| '/api/auth/$'| '/api/autumn/$'+ | '/s/$token/raw'| '/_app/settings/'| '/_authenticated/onboarding/'+ | '/s/$token/'| '/_project/p/$projectId/audit'| '/_project/p/$projectId/backlinks'| '/_project/p/$projectId/brand-lookup'@@ -718,6 +742,8 @@ export interface RootRouteChildren {RReportIdRoute: typeof RReportIdRouteApiAuthSplatRoute: typeof ApiAuthSplatRouteApiAutumnSplatRoute: typeof ApiAutumnSplatRoute+ STokenRawRoute: typeof STokenRawRoute+ STokenIndexRoute: typeof STokenIndexRouteApiGa4OauthCallbackRoute: typeof ApiGa4OauthCallbackRouteApiGscOauthCallbackRoute: typeof ApiGscOauthCallbackRoute}@@ -892,6 +918,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof Char91DotwellKnownChar93OpenaiAppsChallengeRouteImportparentRoute: typeof rootRouteImport}+ '/s/$token/': {+ id: '/s/$token/'+ path: '/s/$token'+ fullPath: '/s/$token/'+ preLoaderRoute: typeof STokenIndexRouteImport+ parentRoute: typeof rootRouteImport+ }'/_authenticated/onboarding/': {id: '/_authenticated/onboarding/'path: '/onboarding'@@ -906,6 +939,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AppSettingsIndexRouteImportparentRoute: typeof AppSettingsRoute}+ '/s/$token/raw': {+ id: '/s/$token/raw'+ path: '/s/$token/raw'+ fullPath: '/s/$token/raw'+ preLoaderRoute: typeof STokenRawRouteImport+ parentRoute: typeof rootRouteImport+ }'/api/autumn/$': {id: '/api/autumn/$'path: '/api/autumn/$'@@ -1328,6 +1368,8 @@ const rootRouteChildren: RootRouteChildren = {RReportIdRoute: RReportIdRoute,ApiAuthSplatRoute: ApiAuthSplatRoute,ApiAutumnSplatRoute: ApiAutumnSplatRoute,+ STokenRawRoute: STokenRawRoute,+ STokenIndexRoute: STokenIndexRoute,ApiGa4OauthCallbackRoute: ApiGa4OauthCallbackRoute,ApiGscOauthCallbackRoute: ApiGscOauthCallbackRoute,}diff --git a/src/routes/_project/p/$projectId/reports/$reportId.tsx b/src/routes/_project/p/$projectId/reports/$reportId.tsxindex 0203a030..5774034a 100644--- a/src/routes/_project/p/$projectId/reports/$reportId.tsx+++ b/src/routes/_project/p/$projectId/reports/$reportId.tsx@@ -5,6 +5,8 @@ import {ChevronLeft,ExternalLink,FileDown,+ Globe,+ Lock,Maximize2,Minimize2,MoreHorizontal,@@ -16,10 +18,12 @@ import { ReportViewer } from "@/client/features/reports/ReportViewer";import {DeleteReportModal,formatCreatedBy,- formatRelativeTime,reportQueryKey,+ ShareReportModal,useDeleteReport,} from "@/client/features/reports/shared";+import { formatRelativeTime } from "@/client/lib/relative-time";+import { isHostedClientAuthMode } from "@/lib/auth-mode";import {getErrorCode,getStandardErrorMessage,@@ -40,9 +44,11 @@ export const Route = createFileRoute(function ReportDetailPage() {const { projectId, reportId } = Route.useParams();+ const hosted = isHostedClientAuthMode();const { full } = Route.useSearch();const navigate = useNavigate({ from: Route.fullPath });const [showDelete, setShowDelete] = useState(false);+ const [showShare, setShowShare] = useState(false);const openedRef = useRef<string | null>(null);const exitRef = useRef<HTMLButtonElement>(null);@@ -144,6 +150,16 @@ function ReportDetailPage() {);}+ // `?print=1` serves the same document with a print() script appended, so the+ // new tab opens the print dialog itself.+ const exportPdf = () => {+ captureClientEvent("report:exported_pdf", {+ project_id: projectId,+ report_id: report.id,+ });+ window.open(`/r/${report.id}?print=1`, "_blank", "noopener");+ };+if (full) {return (<div className="fixed inset-0 z-50 flex flex-col bg-base-100">@@ -204,22 +220,34 @@ function ReportDetailPage() {</dl></div><div className="flex shrink-0 items-center gap-2">- <button- type="button"- className="btn btn-primary btn-sm gap-1.5"- onClick={() => {- captureClientEvent("report:exported_pdf", {- project_id: projectId,- report_id: report.id,- });- // `?print=1` serves the same document with a print() script- // appended, so the new tab opens the print dialog itself.- window.open(`/r/${report.id}?print=1`, "_blank", "noopener");- }}- >- <FileDown className="size-4" />- Export- </button>+ {/* Share links are hosted-only (see shareAccess.ts), so a+ self-hosted deployment keeps Export as its primary action+ rather than offering a button the server would refuse. The+ icon carries the state: a globe once a public link is live, a+ lock while only members can open it. */}+ {hosted ? (+ <button+ type="button"+ className="btn btn-primary btn-sm gap-1.5"+ onClick={() => setShowShare(true)}+ >+ {report.shareToken ? (+ <Globe className="size-4" />+ ) : (+ <Lock className="size-4" />+ )}+ Share+ </button>+ ) : (+ <button+ type="button"+ className="btn btn-primary btn-sm gap-1.5"+ onClick={exportPdf}+ >+ <FileDown className="size-4" />+ Export+ </button>+ )}<PortalMenuariaLabel="Report actions"triggerClassName="btn btn-ghost btn-sm btn-square"@@ -228,6 +256,19 @@ function ReportDetailPage() {>{(close) => (<>+ {hosted ? (+ <li>+ <button+ onClick={() => {+ close();+ exportPdf();+ }}+ >+ <FileDown className="size-4" />+ Export+ </button>+ </li>+ ) : null}<li><buttononClick={() => {@@ -274,6 +315,10 @@ function ReportDetailPage() {<ReportViewer src={`/r/${report.id}`} title={report.title} /></div>+ {hosted && showShare ? (+ <ShareReportModal report={report} onClose={() => setShowShare(false)} />+ ) : null}+{showDelete ? (<DeleteReportModaltitle={report.title}diff --git a/src/routes/r/$reportId.ts b/src/routes/r/$reportId.tsindex e884414f..a1600381 100644--- a/src/routes/r/$reportId.ts+++ b/src/routes/r/$reportId.ts@@ -5,7 +5,7 @@ import { resolveUserContextFromHeaders } from "@/middleware/ensure-user/resolve"import { ProjectRepository } from "@/server/features/projects/repositories/ProjectRepository";import { ReportRepository } from "@/server/features/reports/repositories/ReportRepository";import { asAppError } from "@/server/lib/errors";-import { PRINT_SCRIPT, reportCsp, textResponse } from "@/shared/report-sandbox";+import { reportDocumentResponse, textResponse } from "@/shared/report-sandbox";// The report viewer: the stored document, served byte for byte from the app's// own origin and locked down by REPORT_CSP. A raw-Response route, so no React@@ -20,24 +20,6 @@ const NOT_FOUND_BODY =const reportNotFound = () => textResponse(NOT_FOUND_BODY, 404);-/**- * Appends PRINT_SCRIPT to a stored document, last so it runs after the page.- * The splice happens without parsing a document we did not write, so a report- * ending in a dangling `<script src="…" ` absorbs whatever we put on our tag;- * an attribute-free tag gives such a document nothing but a valueless- * attribute name, and printing simply no-ops there.- */-function withPrintScript(html: string): string {- const tag = `<script>${PRINT_SCRIPT}</script>`;- const bodyClose = html.lastIndexOf("</body>");- if (bodyClose !== -1)- return html.slice(0, bodyClose) + tag + html.slice(bodyClose);- const htmlClose = html.lastIndexOf("</html>");- if (htmlClose !== -1)- return html.slice(0, htmlClose) + tag + html.slice(htmlClose);- return html + tag;-}-async function handleReportRequest(reportId: string,request: Request,@@ -100,20 +82,9 @@ async function handleReportRequest(// the browser's print dialog itself.const print = new URL(request.url).searchParams.get("print") === "1";- return new Response(print ? withPrintScript(html) : html, {- status: 200,- headers: {- "Content-Type": "text/html; charset=utf-8",- "Content-Security-Policy": reportCsp(print),- // The sandbox allows popups to escape, so a link in a report opens a real- // page that would otherwise keep a handle on this tab and be able to- // navigate it. COOP severs that handle. Ignored when framed, which is- // what the in-app viewer wants.- "Cross-Origin-Opener-Policy": "same-origin",- "Referrer-Policy": "no-referrer",- "X-Content-Type-Options": "nosniff",- "Cache-Control": "private, no-store",- },+ return reportDocumentResponse(html, {+ print,+ cacheControl: "private, no-store",});}diff --git a/src/routes/s/$token/index.tsx b/src/routes/s/$token/index.tsxnew file mode 100644index 00000000..123f2a7d--- /dev/null+++ b/src/routes/s/$token/index.tsx@@ -0,0 +1,155 @@+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 marketing site's card. Absolute because a link preview crawler resolves+// og:image against nothing, and the app domain does not serve this asset.+const SOCIAL_CARD_URL = "https://openseo.so/social-card.jpg";++// 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 },+ { property: "og:image", content: SOCIAL_CARD_URL },+ { property: "og:image:width", content: "1200" },+ { property: "og:image:height", content: "630" },+ { 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/routes/s/$token/raw.ts b/src/routes/s/$token/raw.tsnew file mode 100644index 00000000..0226d6bc--- /dev/null+++ b/src/routes/s/$token/raw.ts@@ -0,0 +1,110 @@+import { waitUntil } from "cloudflare:workers";+import { createFileRoute } from "@tanstack/react-router";+import { ReportRepository } from "@/server/features/reports/repositories/ReportRepository";+import {+ SHARE_TOKEN_PATTERN,+ sharesEnabled,+} from "@/server/features/reports/shareAccess";+import { captureServerEvent } from "@/server/lib/posthog";+import { reportDocumentResponse, textResponse } from "@/shared/report-sandbox";+import { sharePath } from "@/shared/report-share";++// The shared report's document, served to anyone holding the token. The twin+// of /r/<reportId>: same stored HTML, same REPORT_CSP sandbox, but authorized+// by the unguessable token instead of a session.+//+// A raw-Response route, so no React and no auth guard runs — and no+// `component`, on purpose: a component would pull this file (and+// `cloudflare:workers` with it) into the client bundle.++// One body for every dead end — unknown token, revoked link, archived project,+// kill switch off. A revoked link must not confirm that it once worked.+const NOT_SHARED_BODY = "This report isn't shared.";++/**+ * A stable pseudonym for one link, so views can be counted per report without+ * a person profile and without putting the token itself (the capability) into+ * PostHog.+ */+async function shareDistinctId(token: string): Promise<string> {+ const digest = await crypto.subtle.digest(+ "SHA-256",+ new TextEncoder().encode(token),+ );+ const hex = [...new Uint8Array(digest)]+ .map((byte) => byte.toString(16).padStart(2, "0"))+ .join("");+ return `share:${hex.slice(0, 16)}`;+}++async function handleSharedReportRequest(+ token: string,+ request: Request,+): Promise<Response> {+ const notShared = () => textResponse(NOT_SHARED_BODY, 404);++ if (!(await sharesEnabled())) return notShared();+ // Shape first, so a scanner walking /s/<anything>/raw costs no query.+ if (!SHARE_TOKEN_PATTERN.test(token)) return notShared();++ const report = await ReportRepository.getSharedReportByToken(token);+ if (!report || report.archived) return notShared();++ // The document is only ever reachable inside the wrapper page's frame, so+ // shared content always carries OpenSEO's chrome; there is no print mode+ // here, because a cancelled print dialog would leave a bare report open+ // top-level on the app domain. Members print from the app. The redirect+ // needs the header to say the request is top-level: a client that sends no+ // Sec-Fetch-Dest at all (an old browser, a link-preview fetcher, curl) would+ // otherwise be bounced to a page whose frame it cannot load either, so an+ // absent header is served the document.+ const dest = request.headers.get("Sec-Fetch-Dest");+ if (dest !== null && dest !== "iframe") {+ return new Response(null, {+ status: 302,+ headers: { Location: sharePath(token), "Cache-Control": "no-store" },+ });+ }++ const html = await ReportRepository.getReportHtml(+ report.projectId,+ report.id,+ );+ if (html === null) return notShared();++ waitUntil(+ (async () => {+ await captureServerEvent({+ distinctId: await shareDistinctId(token),+ event: "report:public_view",+ organizationId: report.organizationId,+ properties: {+ report_id: report.id,+ project_id: report.projectId,+ skill: report.skill,+ // Kept so link-preview bots can be excluded from the count.+ user_agent: request.headers.get("User-Agent"),+ // Readers are anonymous and stay that way: no person profile is+ // created for a share pseudonym.+ $process_person_profile: false,+ },+ });+ })(),+ );++ return reportDocumentResponse(html, {+ cacheControl: "no-store",+ noindex: true,+ });+}++export const Route = createFileRoute("/s/$token/raw")({+ server: {+ handlers: {+ GET: ({ params, request }) =>+ handleSharedReportRequest(params.token, request),+ },+ },+});++export { handleSharedReportRequest, NOT_SHARED_BODY };diff --git a/src/server/features/reports/repositories/ReportRepository.ts b/src/server/features/reports/repositories/ReportRepository.tsindex 51ff80c8..545f880f 100644--- a/src/server/features/reports/repositories/ReportRepository.ts+++ b/src/server/features/reports/repositories/ReportRepository.ts@@ -20,6 +20,8 @@ const metadataColumns = {createdBy: reports.createdBy,createdByUserId: reports.createdByUserId,sizeBytes: reports.sizeBytes,+ shareToken: reports.shareToken,+ sharedAt: reports.sharedAt,createdAt: reports.createdAt,updatedAt: reports.updatedAt,};@@ -180,6 +182,59 @@ async function updateReportContent(params: {);}+// The share link's own read, and the second query here with no project id to+// scope it: `/s/<token>` arrives with a token and nothing else. The token is+// the authorization, so the row is joined to its project for the organization+// id (telemetry grouping) and the archived flag the public page renders.+async function getSharedReportByToken(token: string): Promise<{+ id: string;+ projectId: string;+ organizationId: string;+ title: string;+ summary: string;+ skill: string | null;+ updatedAt: string;+ archived: boolean;+} | null> {+ const [row] = await db+ .select({+ id: reports.id,+ projectId: reports.projectId,+ organizationId: projects.organizationId,+ title: reports.title,+ summary: reports.summary,+ skill: reports.skill,+ updatedAt: reports.updatedAt,+ archivedAt: projects.archivedAt,+ })+ .from(reports)+ .innerJoin(projects, eq(projects.id, reports.projectId))+ .where(eq(reports.shareToken, token))+ .limit(1);+ if (!row) return null;+ const { archivedAt, ...report } = row;+ return { ...report, archived: archivedAt !== null };+}++// Share state only, so minting or revoking a link never touches `updated_at` —+// the app shows "Updated" as when the content last changed, and sharing is not+// a content change.+async function setShareToken(+ projectId: string,+ reportId: string,+ // The service mints both halves, so the token it hands back to the caller+ // and the stamp stored with it come from one clock.+ share: { shareToken: string; sharedAt: string } | null,+): Promise<void> {+ await db+ .update(reports)+ .set({+ shareToken: share?.shareToken ?? null,+ sharedAt: share?.sharedAt ?? null,+ })+ .where(and(eq(reports.id, reportId), eq(reports.projectId, projectId)));+}+/** True when a row was deleted; false when the id is not in this project. */async function deleteReport(projectId: string,@@ -198,6 +253,8 @@ export const ReportRepository = {getReportProjectId,getReportHtml,getReportWithHtml,+ getSharedReportByToken,+ setShareToken,findReportByTitle,countReports,sumReportBytesForOrganization,diff --git a/src/server/features/reports/services/ReportService.test.ts b/src/server/features/reports/services/ReportService.test.tsindex 1e3408b7..3717e5b4 100644--- a/src/server/features/reports/services/ReportService.test.ts+++ b/src/server/features/reports/services/ReportService.test.ts@@ -1,10 +1,19 @@import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ getOptionalEnvValue,+ isHostedServerAuthMode,+} from "@/server/lib/runtime-env";import { formatCount } from "@/shared/format";import {REPORT_MAX_BYTES_PER_ORG,REPORT_MAX_PER_PROJECT,} from "@/types/schemas/reports";-import { deleteReport, getReport, saveReport } from "./ReportService";+import {+ deleteReport,+ getReport,+ ReportService,+ saveReport,+} from "./ReportService";const mocks = vi.hoisted(() => ({listReports: vi.fn(),@@ -15,11 +24,17 @@ const mocks = vi.hoisted(() => ({insertReport: vi.fn(),updateReportContent: vi.fn(),deleteReport: vi.fn(),+ setShareToken: vi.fn(),}));vi.mock("@/server/features/reports/repositories/ReportRepository", () => ({ReportRepository: mocks,}));+vi.mock("@/server/lib/posthog", () => ({ captureServerEvent: vi.fn() }));+vi.mock("@/server/lib/runtime-env", () => ({+ getOptionalEnvValue: vi.fn(),+ isHostedServerAuthMode: vi.fn(),+}));const html = "<!doctype html><html><body>Hi</body></html>";@@ -44,6 +59,8 @@ const storedReport = {createdBy: "Codex",createdByUserId: "user_original",sizeBytes: 42,+ shareToken: null,+ sharedAt: null,createdAt: "2026-09-01T10:00:00.000Z",updatedAt: "2026-09-01T10:00:00.000Z",};@@ -193,3 +210,89 @@ describe("reads and deletes", () => {expect(mocks.deleteReport).toHaveBeenCalledWith("project_1", "report_gone");});});++describe("sharing", () => {+ const share = () =>+ ReportService.shareReport({+ projectId: "project_1",+ reportId: "report_1",+ userId: "user_1",+ organizationId: "org_1",+ });++ beforeEach(() => {+ vi.mocked(isHostedServerAuthMode).mockResolvedValue(true);+ vi.mocked(getOptionalEnvValue).mockResolvedValue(undefined);+ mocks.getReport.mockResolvedValue(storedReport);+ });++ it("mints, revokes and re-mints a different token", async () => {+ const first = await share();++ expect(first.shareToken).toMatch(/^[A-Za-z0-9_-]{32}$/);+ expect(mocks.setShareToken).toHaveBeenCalledWith("project_1", "report_1", {+ shareToken: first.shareToken,+ sharedAt: first.sharedAt,+ });++ mocks.getReport.mockResolvedValue({+ ...storedReport,+ shareToken: first.shareToken,+ sharedAt: first.sharedAt,+ });+ await expect(+ ReportService.unshareReport({+ projectId: "project_1",+ reportId: "report_1",+ userId: "user_1",+ organizationId: "org_1",+ }),+ ).resolves.toMatchObject({ shareToken: null, sharedAt: null });+ expect(mocks.setShareToken).toHaveBeenLastCalledWith(+ "project_1",+ "report_1",+ null,+ );++ mocks.getReport.mockResolvedValue(storedReport);+ const second = await share();+ expect(second.shareToken).not.toBe(first.shareToken);+ });++ // A double-clicked toggle must not invalidate the link the user just copied.+ it("returns the existing token instead of minting a second one", async () => {+ mocks.getReport.mockResolvedValue({+ ...storedReport,+ shareToken: "a".repeat(32),+ sharedAt: "2026-09-10T10:00:00.000Z",+ });++ await expect(share()).resolves.toMatchObject({+ shareToken: "a".repeat(32),+ sharedAt: "2026-09-10T10:00:00.000Z",+ });+ expect(mocks.setShareToken).not.toHaveBeenCalled();+ });++ // A self-hosted deployment cannot serve the link, and the kill switch turns+ // the public routes off, so in either case a minted token is a link that+ // silently does nothing. Refused before the report is even read.+ it.each([+ [+ "the deployment is not hosted",+ () => vi.mocked(isHostedServerAuthMode).mockResolvedValue(false),+ ],+ [+ "the kill switch is off",+ () => vi.mocked(getOptionalEnvValue).mockResolvedValue("false"),+ ],+ ])("refuses to mint when %s", async (_case, arrange) => {+ arrange();++ await expect(share()).rejects.toThrow(+ "Sharing is switched off on this deployment.",+ );+ expect(mocks.setShareToken).not.toHaveBeenCalled();+ expect(mocks.getReport).not.toHaveBeenCalled();+ });+});diff --git a/src/server/features/reports/services/ReportService.ts b/src/server/features/reports/services/ReportService.tsindex 315005c1..2a7bcb94 100644--- a/src/server/features/reports/services/ReportService.ts+++ b/src/server/features/reports/services/ReportService.ts@@ -1,6 +1,9 @@import { ReportRepository } from "@/server/features/reports/repositories/ReportRepository";+import { sharesEnabled } from "@/server/features/reports/shareAccess";import { AppError } from "@/server/lib/errors";+import { captureServerEvent } from "@/server/lib/posthog";import { formatCount } from "@/shared/format";+import { mintShareToken } from "@/shared/report-share";import {REPORT_MAX_BYTES_PER_ORG,REPORT_MAX_HTML_BYTES,@@ -229,6 +232,74 @@ export async function deleteReport(if (!deleted) throw notFound(reportId);}+type ShareParams = {+ projectId: string;+ reportId: string;+ /** From the authenticated context — the telemetry identity, nothing else. */+ userId: string;+ organizationId: string;+};++/**+ * Mints the public link, or returns the existing one. Idempotent on purpose:+ * the modal's toggle can be flipped twice by a double click or a retried+ * mutation, and a second mint would silently break the link the user just+ * copied.+ */+async function shareReport(params: ShareParams): Promise<ReportMetadata> {+ // Refused here rather than only hidden in the UI: the server is the trust+ // boundary. A token minted while sharing is off is a link that silently does+ // nothing, and the user would have copied it believing otherwise.+ if (!(await sharesEnabled())) {+ throw new AppError(+ "VALIDATION_ERROR",+ "Sharing is switched off on this deployment.",+ );+ }++ const report = await getReport(params.projectId, params.reportId);+ if (report.shareToken) return report;++ const shareToken = mintShareToken();+ const sharedAt = new Date().toISOString();+ await ReportRepository.setShareToken(params.projectId, params.reportId, {+ shareToken,+ sharedAt,+ });+ await captureServerEvent({+ distinctId: params.userId,+ event: "report:shared",+ organizationId: params.organizationId,+ properties: {+ project_id: params.projectId,+ report_id: params.reportId,+ skill: report.skill,+ source: "app",+ },+ });+ return { ...report, shareToken, sharedAt };+}++/** Revokes the link by nulling the token. A second call is a no-op. */+async function unshareReport(params: ShareParams): Promise<ReportMetadata> {+ const report = await getReport(params.projectId, params.reportId);+ if (!report.shareToken) return report;++ await ReportRepository.setShareToken(params.projectId, params.reportId, null);+ await captureServerEvent({+ distinctId: params.userId,+ event: "report:unshared",+ organizationId: params.organizationId,+ properties: {+ project_id: params.projectId,+ report_id: params.reportId,+ skill: report.skill,+ source: "app",+ },+ });+ return { ...report, shareToken: null, sharedAt: null };+}+// Shared by the reads and the delete, where `reportId` is a required argument —// so no "omit reportId" hint here; that one belongs to save_report, which has// its own message above.@@ -245,4 +316,6 @@ export const ReportService = {getReport,getReportWithHtml,deleteReport,+ shareReport,+ unshareReport,} as const;diff --git a/src/server/features/reports/shareAccess.ts b/src/server/features/reports/shareAccess.tsnew file mode 100644index 00000000..f37ddf9f--- /dev/null+++ b/src/server/features/reports/shareAccess.ts@@ -0,0 +1,33 @@+import {+ getOptionalEnvValue,+ isHostedServerAuthMode,+} from "@/server/lib/runtime-env";++// The two server-side gates every share path runs: is sharing on at all, and+// does this path segment even look like a token. Server-only, so reading the+// env here cannot drag `cloudflare:workers` into the client bundle — the+// client half of sharing is `sharePath` in @/shared/report-share.++/**+ * Hosted, and not switched off. One predicate rather than two, so the mint,+ * the share page and the raw endpoint cannot disagree about either half.+ *+ * Sharing is a hosted-only feature: a self-hosted deployment is behind+ * Cloudflare Access or has no auth at all, and neither can serve a link to a+ * reader who is not signed in. The `SHARES_ENABLED` kill switch is the+ * operator lever on top of that: sharing is on unless the var is exactly+ * "false", because an unset or misspelled value must not silently break every+ * live link, and the switch exists to be flipped in the dashboard without a+ * deploy.+ */+export async function sharesEnabled(): Promise<boolean> {+ if (!(await isHostedServerAuthMode())) return false;+ return (await getOptionalEnvValue("SHARES_ENABLED")) !== "false";+}++/**+ * The shape check both public entry points run before touching the database, so+ * a scanner walking `/s/<anything>` is answered without a query. Matches what+ * mintShareToken emits: 32 base64url characters.+ */+export const SHARE_TOKEN_PATTERN = /^[A-Za-z0-9_-]{32}$/;diff --git a/src/server/features/reports/sharePage.test.ts b/src/server/features/reports/sharePage.test.tsnew file mode 100644index 00000000..f77825e0--- /dev/null+++ b/src/server/features/reports/sharePage.test.ts@@ -0,0 +1,103 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { loadSharePage } from "./sharePage";++const mocks = vi.hoisted(() => ({+ env: {+ AUTH_MODE: "hosted" as string | undefined,+ SHARES_ENABLED: undefined 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);++// Only what the page reads off the row.+const SHARED_REPORT = {+ title: "badseo.dev SEO audit",+ summary: "\nFix the titles first.\n\nThen the meta descriptions.",+ updatedAt: "2026-09-01T10:00:00.000Z",+ archived: false,+};++beforeEach(() => {+ mocks.env.AUTH_MODE = "hosted";+ mocks.env.SHARES_ENABLED = undefined;+ 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}`,+ updatedAt: "2026-09-01T10:00:00.000Z",+ });+ expect(mocks.setResponseStatus).not.toHaveBeenCalled();+ });++ // The reader is told the project is archived; the report's own title is+ // content the link no longer grants access to.+ it("names the archived state without naming the report", async () => {+ mocks.getSharedReportByToken.mockResolvedValue({+ ...SHARED_REPORT,+ archived: true,+ });++ await expect(loadSharePage(TOKEN)).resolves.toMatchObject({+ state: "archived",+ title: "Report unavailable",+ });+ expect(mocks.setResponseStatus).toHaveBeenCalledWith(404);+ });++ // 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.+ it.each([+ [+ "an unknown or revoked token",+ () => mocks.getSharedReportByToken.mockResolvedValue(null),+ ],+ [+ "the kill switch turned off",+ () => {+ mocks.env.SHARES_ENABLED = "false";+ },+ ],+ // Sharing is hosted-only: a self-hosted deployment answers as if the+ // link had never existed.+ [+ "a deployment that is not hosted",+ () => {+ mocks.env.AUTH_MODE = "cloudflare_access";+ },+ ],+ ])("reports missing for %s", async (_case, arrange) => {+ arrange();++ await expect(loadSharePage(TOKEN)).resolves.toMatchObject({+ state: "missing",+ });+ expect(mocks.setResponseStatus).toHaveBeenCalledWith(404);+ });++ it("reports missing for a malformed token without querying", async () => {+ await expect(loadSharePage("nope")).resolves.toMatchObject({+ state: "missing",+ });+ expect(mocks.getSharedReportByToken).not.toHaveBeenCalled();+ });+});diff --git a/src/server/features/reports/sharePage.ts b/src/server/features/reports/sharePage.tsnew file mode 100644index 00000000..8e703043--- /dev/null+++ b/src/server/features/reports/sharePage.ts@@ -0,0 +1,93 @@+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";++/** 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;+ /** 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,+ 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");++ return {+ state: "ok",+ title: report.title,+ description: shareDescription(report.summary),+ url: canonical,+ updatedAt: report.updatedAt,+ };+ },+);diff --git a/src/server/features/reports/shareRawRoute.test.ts b/src/server/features/reports/shareRawRoute.test.tsnew file mode 100644index 00000000..7f9f6865--- /dev/null+++ b/src/server/features/reports/shareRawRoute.test.ts@@ -0,0 +1,145 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ handleSharedReportRequest,+ NOT_SHARED_BODY,+} from "@/routes/s/$token/raw";+import { REPORT_CSP } from "@/shared/report-sandbox";++const mocks = vi.hoisted(() => ({+ env: {+ AUTH_MODE: "hosted" as string | undefined,+ SHARES_ENABLED: undefined as string | undefined,+ },+ getSharedReportByToken: vi.fn(),+ getReportHtml: vi.fn(),+}));++vi.mock("cloudflare:workers", () => ({+ env: mocks.env,+ waitUntil: (promise: Promise<unknown>) => void promise,+}));+vi.mock("@/server/lib/posthog", () => ({ captureServerEvent: vi.fn() }));+vi.mock("@/server/features/reports/repositories/ReportRepository", () => ({+ ReportRepository: {+ getSharedReportByToken: mocks.getSharedReportByToken,+ getReportHtml: mocks.getReportHtml,+ },+}));++const TOKEN = "a".repeat(32);+const HTML = "<!doctype html><html><body>report</body></html>";++/** Framed is the normal case; the `Sec-Fetch-Dest` header is what says so. */+const framed = () =>+ new Request(`https://app.example.com/s/${TOKEN}/raw`, {+ headers: { "Sec-Fetch-Dest": "iframe" },+ });++const topLevel = () =>+ new Request(`https://app.example.com/s/${TOKEN}/raw`, {+ headers: { "Sec-Fetch-Dest": "document" },+ });++/** A client that sends no `Sec-Fetch-Dest` at all: curl, an old browser. */+const noFetchMetadata = () =>+ new Request(`https://app.example.com/s/${TOKEN}/raw`);++const SHARED_REPORT = {+ id: "report_1",+ projectId: "project_1",+ organizationId: "org_1",+ title: "badseo.dev SEO audit",+ summary: "One clear verdict.",+ skill: "seo-audit",+ updatedAt: "2026-09-01T10:00:00.000Z",+ archived: false,+};++beforeEach(() => {+ mocks.env.AUTH_MODE = "hosted";+ mocks.env.SHARES_ENABLED = undefined;+ mocks.getSharedReportByToken.mockResolvedValue(SHARED_REPORT);+ mocks.getReportHtml.mockResolvedValue(HTML);+});++describe("handleSharedReportRequest", () => {+ it("serves the stored document to the frame with the sandbox headers", async () => {+ const response = await handleSharedReportRequest(TOKEN, framed());++ expect(response.status).toBe(200);+ expect(await response.text()).toBe(HTML);+ expect(Object.fromEntries(response.headers)).toEqual({+ "content-type": "text/html; charset=utf-8",+ "content-security-policy": REPORT_CSP,+ "cross-origin-opener-policy": "same-origin",+ "referrer-policy": "no-referrer",+ "x-content-type-options": "nosniff",+ "x-robots-tag": "noindex, nofollow",+ "cache-control": "no-store",+ });+ });++ // The whole point of the wrapper page: shared content always carries our+ // chrome, so the document is unreachable on its own.+ it("bounces a top-level request to the wrapped page", async () => {+ const response = await handleSharedReportRequest(TOKEN, topLevel());++ expect(response.status).toBe(302);+ expect(response.headers.get("location")).toBe(`/s/${TOKEN}`);+ expect(mocks.getReportHtml).not.toHaveBeenCalled();+ });++ // The redirect needs the header to say so. Bouncing a client that sends no+ // fetch metadata would send it to a page whose frame it cannot load either.+ it("serves the document when the request carries no Sec-Fetch-Dest", async () => {+ const response = await handleSharedReportRequest(TOKEN, noFetchMetadata());++ expect(response.status).toBe(200);+ expect(await response.text()).toBe(HTML);+ });++ it.each([+ [+ "an unknown or revoked token",+ () => mocks.getSharedReportByToken.mockResolvedValue(null),+ ],+ // Restoring the project brings the link back, so this is not a 404 body+ // that says anything different.+ [+ "an archived project",+ () =>+ mocks.getSharedReportByToken.mockResolvedValue({+ ...SHARED_REPORT,+ archived: true,+ }),+ ],+ [+ "the kill switch turned off",+ () => {+ mocks.env.SHARES_ENABLED = "false";+ },+ ],+ // Sharing is hosted-only.+ [+ "a deployment that is not hosted",+ () => {+ mocks.env.AUTH_MODE = "cloudflare_access";+ },+ ],+ ])("answers the same 404 for %s", async (_case, arrange) => {+ arrange();++ const response = await handleSharedReportRequest(TOKEN, framed());++ expect(response.status).toBe(404);+ expect(await response.text()).toBe(NOT_SHARED_BODY);+ expect(mocks.getReportHtml).not.toHaveBeenCalled();+ });++ it("answers a malformed token without querying", async () => {+ const response = await handleSharedReportRequest("nope", framed());++ expect(response.status).toBe(404);+ expect(mocks.getSharedReportByToken).not.toHaveBeenCalled();+ });+});diff --git a/src/server/mcp/tools/report-tools.ts b/src/server/mcp/tools/report-tools.tsindex 799b7090..2a5453c6 100644--- a/src/server/mcp/tools/report-tools.ts+++ b/src/server/mcp/tools/report-tools.ts@@ -1,3 +1,4 @@+import { omit } from "remeda";import { z } from "zod";import { ReportService } from "@/server/features/reports/services/ReportService";import { ReportTemplateService } from "@/server/features/reports/services/ReportTemplateService";@@ -37,7 +38,17 @@ const size = (bytes: number) =>? `${formatCount(bytes)} bytes`: `${formatCount(Math.round(bytes / 1000))} KB`;-const metaLine = (report: ReportMetadata) =>+// The public share token is a capability; only the app mints and shows it.+// Agents get every other column.+const forAgent = (report: ReportMetadata) =>+ omit(report, ["shareToken", "sharedAt"]);++const metaLine = (+ report: Pick<+ ReportMetadata,+ "skill" | "createdBy" | "updatedAt" | "sizeBytes"+ >,+) =>[report.skill ?? "no skill",report.createdBy,@@ -228,7 +239,7 @@ export const listReportsTool = {});const rows = reports.map((report) => ({- ...report,+ ...forAgent(report),summary: truncatePreview(report.summary),}));@@ -342,7 +353,7 @@ export const getReportTool = {meta: buildProjectMeta(context, args.projectId, path),structuredContent: {report: {- ...report,+ ...forAgent(report),htmlBytes: report.sizeBytes,url,},diff --git a/src/serverFunctions/reports.ts b/src/serverFunctions/reports.tsindex d4336ebf..72d04749 100644--- a/src/serverFunctions/reports.ts+++ b/src/serverFunctions/reports.ts@@ -96,6 +96,37 @@ export const getReport = createServerFn({ method: "POST" })return withNames;});+/**+ * Mints (or returns) the report's public link. The token alone comes back —+ * the app builds `<origin>/s/<token>` client-side, so the same server works on+ * app.openseo.so and a self-hosted hostname without knowing either.+ */+export const shareReport = createServerFn({ method: "POST" })+ .middleware(requireProjectContext)+ .validator(reportRefSchema)+ .handler(async ({ data, context }) => {+ const report = await ReportService.shareReport({+ projectId: context.projectId,+ reportId: data.reportId,+ userId: context.userId,+ organizationId: context.organizationId,+ });+ return { shareToken: report.shareToken, sharedAt: report.sharedAt };+ });++export const unshareReport = createServerFn({ method: "POST" })+ .middleware(requireProjectContext)+ .validator(reportRefSchema)+ .handler(async ({ data, context }) => {+ const report = await ReportService.unshareReport({+ projectId: context.projectId,+ reportId: data.reportId,+ userId: context.userId,+ organizationId: context.organizationId,+ });+ return { shareToken: report.shareToken, sharedAt: report.sharedAt };+ });+export const deleteReport = createServerFn({ method: "POST" }).middleware(requireProjectContext).validator(reportRefSchema)diff --git a/src/shared/report-sandbox.ts b/src/shared/report-sandbox.tsindex c62a058d..d6ce4bcb 100644--- a/src/shared/report-sandbox.ts+++ b/src/shared/report-sandbox.ts@@ -80,3 +80,50 @@ export function textResponse(body: string, status: number): Response {},});}++/**+ * Appends PRINT_SCRIPT to a stored document, last so it runs after the page.+ * The splice happens without parsing a document we did not write, so a report+ * ending in a dangling `<script src="…" ` absorbs whatever we put on our tag;+ * an attribute-free tag gives such a document nothing but a valueless+ * attribute name, and printing simply no-ops there.+ */+function withPrintScript(html: string): string {+ const tag = `<script>${PRINT_SCRIPT}</script>`;+ const bodyClose = html.lastIndexOf("</body>");+ if (bodyClose !== -1)+ return html.slice(0, bodyClose) + tag + html.slice(bodyClose);+ const htmlClose = html.lastIndexOf("</html>");+ if (htmlClose !== -1)+ return html.slice(0, htmlClose) + tag + html.slice(htmlClose);+ return html + tag;+}++/**+ * The one response both report documents are served with — `/r/<id>` for a+ * member and `/s/<token>/raw` for a link holder — so the sandbox, the print+ * script and the header set cannot drift between them. Only the cache scope+ * and the robots tag differ: the public document is the one search engines+ * could reach.+ */+export function reportDocumentResponse(+ html: string,+ options: { print?: boolean; cacheControl: string; noindex?: boolean },+): Response {+ return new Response(options.print ? withPrintScript(html) : html, {+ status: 200,+ headers: {+ "Content-Type": "text/html; charset=utf-8",+ "Content-Security-Policy": reportCsp(options.print),+ // The sandbox allows popups to escape, so a link in a report opens a+ // real page that would otherwise keep a handle on this tab and be able+ // to navigate it. COOP severs that handle. Ignored when framed, which is+ // what both viewers want.+ "Cross-Origin-Opener-Policy": "same-origin",+ "Referrer-Policy": "no-referrer",+ "X-Content-Type-Options": "nosniff",+ ...(options.noindex ? { "X-Robots-Tag": "noindex, nofollow" } : {}),+ "Cache-Control": options.cacheControl,+ },+ });+}diff --git a/src/shared/report-share.ts b/src/shared/report-share.tsnew file mode 100644index 00000000..f891e175--- /dev/null+++ b/src/shared/report-share.ts@@ -0,0 +1,20 @@+// Shared vocabulary for public share links: the mint, and the path the two+// routes and the app all build. The server-only halves (the kill switch, the+// token shape check) live in @/server/features/reports/shareAccess.++/**+ * 24 random bytes rendered base64url: 192 bits of entropy in exactly 32+ * characters, with no padding and nothing to percent-encode in a path segment.+ * The token IS the capability — there is no second factor on `/s/<token>` — so+ * it comes from `crypto.getRandomValues`, never `Math.random` or a uuid.+ */+export function mintShareToken(): string {+ const bytes = crypto.getRandomValues(new Uint8Array(24));+ return btoa(String.fromCharCode(...bytes))+ .replaceAll("+", "-")+ .replaceAll("/", "_")+ .replaceAll("=", "");+}++/** The public path for a token. One definition, used by both routes and the app. */+export const sharePath = (token: string) => `/s/${token}`;diff --git a/src/types/schemas/reports.ts b/src/types/schemas/reports.tsindex 86cd9ee9..7dc524d9 100644--- a/src/types/schemas/reports.ts+++ b/src/types/schemas/reports.ts@@ -57,6 +57,14 @@ export type ReportMetadata = {createdByUserId: string;/** UTF-8 byte length of the stored document. */sizeBytes: number;+ /**+ * The public share token, or null when the report is not shared. The app+ * builds the link from it (`<origin>/s/<token>`) rather than storing a URL,+ * so the same row works on the hosted domain and a self-hosted one.+ */+ shareToken: string | null;+ /** When the current share token was minted, or null when not shared. */+ sharedAt: string | null;createdAt: string;updatedAt: string;};diff --git a/web/content/docs/skills/seo-report.mdx b/web/content/docs/skills/seo-report.mdxindex 683c9080..82ce674f 100644--- a/web/content/docs/skills/seo-report.mdx+++ b/web/content/docs/skills/seo-report.mdx@@ -18,10 +18,14 @@ You do not run it on its own. When your agent finishes an audit, a keyword study## What you get back-A report page in your project with a title that names the subject and the period, like "badseo.dev SEO audit, Sep 2026". Open it from the Reports page in the sidebar, then click Export to save a PDF. The menu beside it opens the report full screen or in its own tab.+A report page in your project with a title that names the subject and the period, like "badseo.dev SEO audit, Sep 2026". Open it from the Reports page in the sidebar. The menu beside it exports a PDF, opens the report full screen, or opens it in its own tab.Reports are free. They do not spend credits, and there is no practical limit on how many a project holds. The Reports page shows the 100 most recent.+## Sharing a report++On openseo.so, open a report, click Share and turn on Public link. Send the link to a client or a teammate; they do not need an OpenSEO account. It always shows the latest saved version, and it is not indexed by search engines. Turn the toggle off and the link stops working.+## How to get the best result- Ask for a workflow, not for a report: "audit badseo.dev" produces one on its own.