Skip to content

Open source alternative to Semrush and Ahrefs

Render JavaScript in site audits: Cloudflare first, Context fallback, credit-hold billing (EVE-217) (#670)

Ben Senescu564f21d0a84d
diff --git a/.agents/PAPERCUTS.md b/.agents/PAPERCUTS.md
index ca35870a..d747c3d0 100644
--- a/.agents/PAPERCUTS.md
+++ b/.agents/PAPERCUTS.md
@@ -10,6 +10,8 @@ data, or sensitive paths.
## Open
+- [ ] `2026-09-30T23:24:29Z` — `claude` — An `ENV_PREVIEW` secret without `AUTH_MODE=local_noauth` makes the PR preview deploy fall back to `cloudflare_access`, which provisions a self-host Access app. The deploy then fails with "Could not read the Zero Trust organization: Unauthorized", because the CI token has no Access permissions. The error suggests `pnpm alchemy login --configure`, which cannot fix CI. Check `AUTH_MODE` in the workflow's "Derive preview URL" step, beside the existing `WORKERS_SUBDOMAIN` check.
+- [ ] `2026-09-30T22:10:17Z` — `claude` — Since #784 moved `@tanstack/react-start` to 1.168.60, `pnpm vite build` rewrites the committed `src/routeTree.gen.ts` with a new import order (about 1,000 changed lines, identical routes), which leaves every local build with a dirty tree. Commit the regenerated file on main once.
- [ ] `2026-09-30T19:03:30Z` — `codex` — The `no-array-sort` lint diagnostic recommends `toSorted()`, but the configured TypeScript library rejects it. Use the existing Remeda `sortBy` helper; align the lint guidance with the supported library target.
- [ ] `2026-09-30T07:08:59Z` — `claude` — On a clone of the origin repo, `git tag --sort=-creatordate | head -1` (openseo-release-notes step 2) and `pnpm release:notes` (which defaults `--from` to the latest local semver tag) both resolve to `v0.0.6`, because release tags are published only on `every-app/open-seo`; the real base had to come from `gh release list --repo every-app/open-seo`. Have the skill and script read the latest release from the public repo instead of local tags.
- [ ] `2026-09-30T07:08:59Z` — `claude` — openseo-release-notes says to look up `(#NN)` on `bensenescu/open-seo` first and fall back to `every-app/open-seo`, but PR numbers collide across the two repos: the commit "Rank Tracking strategy library (#340)" is `every-app/open-seo#340`, while `bensenescu/open-seo#340` is an unrelated merged PR, so the origin-first lookup silently returns the wrong one. Tell the skill to compare the fetched PR title with the commit subject and retry on the public repo when they differ.
diff --git a/.env.example b/.env.example
index 15612ff2..5d05cb10 100644
--- a/.env.example
+++ b/.env.example
@@ -49,3 +49,10 @@
# GOOGLE_CLIENT_ID=replace-with-your-google-oauth-client-id
# GOOGLE_CLIENT_SECRET=replace-with-your-google-oauth-client-secret
# BETTER_AUTH_SECRET=replace-with-a-long-random-secret-at-least-32-characters
+
+# Optional: Context.dev key for the site audit "Render JavaScript" option.
+# Docker has no browser, so the option is disabled until this is set.
+# CONTEXT_API_KEY=
+# Local development only: attach a remote Cloudflare Browser Run binding to
+# the audit worker (needs `wrangler login`).
+# AUDIT_BROWSER_RENDERING=true
diff --git a/deploy/.env.preview.example b/deploy/.env.preview.example
index 045988e1..6cd327a3 100644
--- a/deploy/.env.preview.example
+++ b/deploy/.env.preview.example
@@ -31,3 +31,7 @@ AUTH_MODE=local_noauth
# BYPASS_EMAIL_VERIFICATION=true
# GOOGLE_CLIENT_ID=
# GOOGLE_CLIENT_SECRET=
+
+# Optional: Context.dev key for the site audit "Render JavaScript" option.
+# Cloudflare Browser Run renders first; Context renders the pages it cannot.
+# CONTEXT_API_KEY=
diff --git a/deploy/.env.production.example b/deploy/.env.production.example
index 2f1c7893..59186629 100644
--- a/deploy/.env.production.example
+++ b/deploy/.env.production.example
@@ -44,3 +44,7 @@ DATABASE_PROVIDER=postgres
# POSTHOG_HOST=
# OPENROUTER_API_KEY=
# OPENROUTER_MODEL=
+
+# Optional: Context.dev key for the site audit "Render JavaScript" option.
+# Cloudflare Browser Run renders first; Context renders the pages it cannot.
+# CONTEXT_API_KEY=
diff --git a/deploy/.env.selfhost.example b/deploy/.env.selfhost.example
index 64d4eef1..7e59f616 100644
--- a/deploy/.env.selfhost.example
+++ b/deploy/.env.selfhost.example
@@ -19,6 +19,11 @@ ACCESS_ALLOWED_EMAILS=
# OPENROUTER_API_KEY=
# OPENROUTER_MODEL=
+# Optional: Context.dev fallback for the site audit "Render JavaScript" option.
+# Cloudflare Browser Run renders first; Context renders the pages it cannot
+# (a paid Workers plan is required) — docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md
+# CONTEXT_API_KEY=
+
# Your own PostHog product analytics
# POSTHOG_PUBLIC_KEY=
# POSTHOG_HOST=
diff --git a/deploy/alchemy/alchemy.run.ts b/deploy/alchemy/alchemy.run.ts
index f44c4c82..5df2b339 100644
--- a/deploy/alchemy/alchemy.run.ts
+++ b/deploy/alchemy/alchemy.run.ts
@@ -272,6 +272,7 @@ const dataEnv = {
GOOGLE_CLIENT_SECRET: optionalSecret("GOOGLE_CLIENT_SECRET"),
OPENROUTER_API_KEY: optionalSecret("OPENROUTER_API_KEY"),
OPENROUTER_MODEL: optionalVar("OPENROUTER_MODEL"),
+ CONTEXT_API_KEY: optionalSecret("CONTEXT_API_KEY"),
AUTUMN_SECRET_KEY: optionalSecret("AUTUMN_SECRET_KEY"),
AUTUMN_WEBHOOK_SECRET: optionalSecret("AUTUMN_WEBHOOK_SECRET"),
DUB_API_KEY: optionalSecret("DUB_API_KEY"),
@@ -397,6 +398,8 @@ export default Alchemy.Stack(
// attacker-influenced HTML, so it gets only the secrets its code
// path reads — DataForSEO (Lighthouse), Autumn (metering), PostHog
// (capture). No auth/OAuth/Loops/Turnstile secrets.
+ BROWSER: Cloudflare.Browser(),
+ CONTEXT_API_KEY: dataEnv.CONTEXT_API_KEY,
DATAFORSEO_API_KEY: dataEnv.DATAFORSEO_API_KEY,
AUTUMN_SECRET_KEY: dataEnv.AUTUMN_SECRET_KEY,
POSTHOG_PUBLIC_KEY: dataEnv.POSTHOG_PUBLIC_KEY,
@@ -460,6 +463,9 @@ export default Alchemy.Stack(
AUTH_MODE: authMode,
DATABASE_PROVIDER: databaseProvider || "d1",
BETTER_AUTH_URL: authUrl,
+ // The audit worker above always binds BROWSER; the app worker checks
+ // this before it offers "Render JavaScript".
+ AUDIT_BROWSER_RENDERING: "true",
TEAM_DOMAIN: access.teamDomain,
POLICY_AUD: access.policyAud,
diff --git a/docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md b/docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md
index c7c0b89d..6527573c 100644
--- a/docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md
+++ b/docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md
@@ -1,6 +1,6 @@
# Cloudflare Self-Hosting: Operations
-Day-to-day tasks after [initial setup](./SELF_HOSTING_CLOUDFLARE.md): connect the MCP server and manage telemetry. Updating and teammate access are covered in the [deploy guide](./SELF_HOSTING_CLOUDFLARE.md) (or the [legacy page](./SELF_HOSTING_CLOUDFLARE_LEGACY.md) for pre-alchemy deployments).
+Day-to-day tasks after [initial setup](./SELF_HOSTING_CLOUDFLARE.md): connect the MCP server, render JavaScript in site audits, and manage telemetry. Updating and teammate access are covered in the [deploy guide](./SELF_HOSTING_CLOUDFLARE.md) (or the [legacy page](./SELF_HOSTING_CLOUDFLARE_LEGACY.md) for pre-alchemy deployments).
## Connect the MCP server through Cloudflare Access
@@ -26,6 +26,16 @@ MCP clients should connect to:
https://YOUR_WORKER_HOSTNAME/mcp
```
+## Render JavaScript in site audits
+
+Site Audit can load pages in a browser before analyzing them. Turn on **Render JavaScript** when starting an audit if the site builds its content or links client-side (React and other single-page apps). Rendered audits take longer.
+
+Rendering uses [Cloudflare Browser Run](https://developers.cloudflare.com/browser-run/) on your own Cloudflare account. The deploy binds a browser to the audit Worker, so the toggle works with no extra setup. **Rendering needs a paid Workers plan.** The free plan allows one browser action every ten seconds, which is too slow for a crawl. The paid plan includes 10 browser hours a month, then bills $0.09 per browser hour.
+
+Some sites block Cloudflare's browser. To render those pages through [Context.dev](https://www.context.dev) instead, create a Context account, set `CONTEXT_API_KEY` in `.env.selfhost`, and redeploy. OpenSEO calls Context only for pages that Browser Run could not render, and each of those pages uses one Context credit on your Context account.
+
+Docker deployments have no browser. On Docker, set `CONTEXT_API_KEY` in `.env.local` to render every page through Context. Until the key is set, the **Render JavaScript** toggle stays disabled with a setup note.
+
## Telemetry
OpenSEO collects anonymized telemetry for core usage events: heartbeats with aggregate counts (installs, users, projects, feature usage) tied to a random install ID, sent every 5 minutes during the first two hours after install, then at most once daily. No URLs, keywords, prompts, emails, or IP-derived location are collected, and idle installs send nothing.
diff --git a/docs/maintainers/SITE_AUDIT_RENDERING.md b/docs/maintainers/SITE_AUDIT_RENDERING.md
new file mode 100644
index 00000000..5793d290
--- /dev/null
+++ b/docs/maintainers/SITE_AUDIT_RENDERING.md
@@ -0,0 +1,136 @@
+# Site audit JavaScript rendering
+
+"Render JavaScript" is an option on the site audit start form and the
+`run_site_audit` MCP tool. A rendered audit reads the content, headings and
+links that JavaScript loads.
+
+## Availability
+
+Two renderers exist: [Cloudflare Browser Run](https://developers.cloudflare.com/browser-run/)
+through the audit worker's `BROWSER` binding, and [Context.dev](https://context.dev)
+through `CONTEXT_API_KEY`. The option works when either exists:
+
+- **Hosted and previews:** both. Every account sees the option and pays with
+ usage credits.
+- **Self-hosted Cloudflare (Alchemy):** the deploy binds Browser Run, so the
+ option always works. The operator's Cloudflare account pays, and a paid Workers plan is
+ required (the free plan allows one browser action every ten seconds).
+ `CONTEXT_API_KEY` adds the Context fallback on the operator's Context account.
+- **Docker and legacy Wrangler installs:** no browser. The option works only
+ with `CONTEXT_API_KEY`; otherwise the toggle is shown disabled with a setup
+ note.
+- **Local development:** `AUDIT_BROWSER_RENDERING=true` attaches a remote
+ Browser Run binding to the audit worker (needs `wrangler login`).
+
+`isAuditRenderingAllowed` in `rendering-policy.ts` is the single check. The app
+worker has no browser binding of its own, so Alchemy sets
+`AUDIT_BROWSER_RENDERING=true` on it whenever it binds `BROWSER` to the audit
+worker. The auth mode says nothing about which renderer exists.
+
+## How a page is rendered
+
+1. The crawler fetches the page directly, as before.
+2. The page is rendered when the direct fetch returned readable HTML with a
+ 2xx status, or HTML behind a bot challenge (any `blocked` result except a
+ 401 login wall). Redirects, non-HTML files, origin errors, login walls and
+ rate limits keep their existing paths.
+3. Cloudflare renders first. Context renders only when Cloudflare fails, is
+ challenged, or sees an origin error. Context costs about five times as much
+ per page. Cloudflare always identifies Browser Run as a bot, so sites behind
+ Cloudflare's own bot protection render through Context.
+4. The rendered document replaces the direct body for analysis. The direct
+ response's timing and header directives stay authoritative, and so does
+ its status, except behind a challenge. There the page takes the status
+ Browser Run loaded, or 200 from Context, which reports no status and
+ returns only pages that loaded. Recording a status keeps every page field
+ as it is; an earlier version rescued blocked pages with an unknown status,
+ which made those fields nullable.
+5. A rendered document that looks like a challenge is classified `blocked`,
+ and one still showing the app's loading shell gets the same "content may
+ require JavaScript" warning as an unrendered shell.
+
+A render that fails on every available renderer, or returns an unusable
+document (wrong final URL, empty, still loading), makes the page an unread
+`error` page. A challenge that neither renderer passes stays `blocked`. A
+rendered document over 1 MiB keeps its first 1 MiB, the same bound the direct
+crawl reads. The audit never audits the unrendered shell in its place, and paid
+calls are never retried automatically.
+
+## Billing
+
+Rates live in `src/shared/audit-rendering.ts`, shared by the launch form, the
+MCP tool description, the reservation and the settlement:
+
+- **Cloudflare:** every attempt is billed as its full 20 second timeout at
+ $0.09 per browser hour ($0.0005), not its measured time. A flat price per
+ attempt needs no millisecond accounting and makes the low estimate exact.
+- **Context:** the credits Context reports, including on error responses, at
+ $0.0025 each. A failure that reports no usage is not charged.
+
+Both convert through the standard markup: about 0.64 usage credits per
+Cloudflare page and 3.84 per page that falls back to Context.
+
+Hosted rendering uses Autumn balance locks: one reservation when the audit
+starts, one settlement when it ends. It takes and settles them with the same
+`holdCredits` and `finalizeHold` helpers that hold every DataForSEO call, so a
+timed-out Autumn check fails closed instead of reading as a hold, and a
+retried finalize cannot charge twice. Unlike a single DataForSEO call, one
+audit's hold is split: the monthly balance covers what it can and top-up
+covers the rest.
+
+1. `startAudit` locks the worst case, page limit × the fallback rate, from the
+ monthly balance first and top-up for the remainder. Not enough across both
+ refuses the audit with `INSUFFICIENT_CREDITS` before the workflow starts.
+ The lock ids travel in the workflow params.
+2. Each crawl chunk counts Cloudflare attempts and Context credits and returns
+ them in its step result. Chunks make no Autumn calls.
+3. The workflow sums the checkpointed chunk counts. At the end, whether the
+ audit completed or failed, one step confirms the locks for the credits used,
+ monthly first, and releases the rest.
+4. Locks expire after at most 24 hours. An audit that dies without settling
+ returns the hold to the customer on its own.
+5. A rendered audit crawls at most 1,000 pages (`RENDERED_MAX_AUDIT_PAGES`),
+ enforced like the plan page limits: `startAudit` refuses more with
+ `AUDIT_PAGE_LIMIT_EXCEEDED`, and the launch form caps its page input. At
+ the 20 second worst case per Cloudflare attempt, that keeps a rendered
+ crawl well inside the lock's 24 hours, so settlement finds its lock.
+
+What we absorb rather than charge: renders in a chunk attempt that failed
+before returning its counts, a settlement that Autumn rejects, usage beyond
+the hold (a retried chunk can render a page twice).
+
+Alternatives considered:
+
+- **Per-chunk deductions** (the first release): a failed deduction was logged
+ while the audit kept spending, and an empty balance mid-audit silently
+ switched the rest of the crawl to plain fetching.
+- **Charging up front with a refund:** needs a manual refund on every failure
+ path, and overcharges when the workflow dies.
+- **Per-page billing:** hundreds of Autumn calls per audit.
+
+## Open items
+
+- **Context rate limits.** Context's Developer plan allows 60 calls a minute,
+ and a busy crawl can exceed that when many pages fall back. A Context 429
+ makes the page an unread `error` page. `site_audit:render` logs each Context
+ `httpStatus`, so measure real 429 rates first. If they matter, pause the
+ chunk on a Context 429 the way the crawler pauses on an origin 429
+ (`crawl-throttle.ts`).
+- **Deleting a running rendered audit.** The workflow stops before it settles,
+ so the hold stays until the lock expires and the rendered pages are not
+ charged.
+- **Context pricing tier.** The Context rate in `audit-rendering.ts` assumes
+ the Developer plan. Update it when the hosted account's plan is chosen.
+
+## Configuration
+
+Alchemy binds `BROWSER` and passes `CONTEXT_API_KEY` to the audit worker, and
+passes `CONTEXT_API_KEY` to the app worker for the availability check. Docker
+and local development read the key from `.env.local` or `.dev.vars`.
+
+## References
+
+- [Cloudflare Browser Run pricing](https://developers.cloudflare.com/browser-run/pricing/)
+- [Context HTML scrape](https://docs.context.dev/api-reference/web-scraping/html)
+- [Context pricing](https://context.dev/pricing)
+- [Autumn balance locking](https://docs.useautumn.com/documentation/customers/balance-locking)
diff --git a/plugins/openseo/.claude-plugin/plugin.json b/plugins/openseo/.claude-plugin/plugin.json
index 6924696e..0be40884 100644
--- a/plugins/openseo/.claude-plugin/plugin.json
+++ b/plugins/openseo/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "openseo",
"displayName": "OpenSEO",
- "version": "1.0.6",
+ "version": "1.0.7",
"description": "Without good data, your agent gives generic advice. Keyword research, competitor research, backlinks, and site audits. All for $10/month.",
"author": {
"name": "OpenSEO",
diff --git a/plugins/openseo/.codex-plugin/plugin.json b/plugins/openseo/.codex-plugin/plugin.json
index 4ef8283d..df17e17c 100644
--- a/plugins/openseo/.codex-plugin/plugin.json
+++ b/plugins/openseo/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openseo",
- "version": "1.0.6",
+ "version": "1.0.7",
"description": "Without good data, your agent gives generic advice. Keyword research, competitor research, backlinks, and site audits. All for $10/month.",
"author": {
"name": "OpenSEO",
diff --git a/plugins/openseo/.cursor-plugin/plugin.json b/plugins/openseo/.cursor-plugin/plugin.json
index ec916622..178a1aad 100644
--- a/plugins/openseo/.cursor-plugin/plugin.json
+++ b/plugins/openseo/.cursor-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openseo",
- "version": "1.0.6",
+ "version": "1.0.7",
"description": "SEO made simple. Research keywords and competitors, audit sites, track rankings, and use Search Console data from your agent.",
"author": {
"name": "Every App, Inc",
diff --git a/src/client/features/audit/AuditDetail.tsx b/src/client/features/audit/AuditDetail.tsx
index 3c3db80d..df7f5be1 100644
--- a/src/client/features/audit/AuditDetail.tsx
+++ b/src/client/features/audit/AuditDetail.tsx
@@ -104,9 +104,17 @@ export function AuditDetail({
// banner and the zero-page banner, so the zero-page banner doesn't flash.
const failedWithoutResults =
isFailed && resultsQuery.isSuccess && !failedWithResults;
- // A completed crawl that reached one page or none was blocked by the site.
+ const results = resultsQuery.data;
+ // A completed crawl that reached one page or none was blocked by the site,
+ // unless that page is an app shell, which the results explain instead.
// A failed audit stopped on our side, so it gets the error code instead.
- const showBlockedCta = isComplete && status.pagesCrawled <= 1;
+ const siteBlocked =
+ isComplete &&
+ status.pagesCrawled <= 1 &&
+ results !== undefined &&
+ !results.issues.some(
+ (issue) => issue.issueType === "javascript-rendering-suspected",
+ );
return (
<div className="px-4 py-4 md:px-6 md:py-6 pb-24 md:pb-8 overflow-auto">
@@ -153,15 +161,17 @@ export function AuditDetail({
</Alert>
)}
- {showBlockedCta && (
+ {siteBlocked && results && (
<Alert variant="warning">
<AlertCircle />
<AlertTitle>
- Site audit couldn't fully crawl this website.
+ This site's bot protection blocked our crawler.
</AlertTitle>
<AlertDescription>
- Sorry! This site's bot protection blocked our crawler.{" "}
- <BotProtectionAdvice />
+ <BotProtectionAdvice
+ projectId={projectId}
+ rendered={results.audit.config.renderJavaScript === true}
+ />
</AlertDescription>
</Alert>
)}
@@ -194,6 +204,7 @@ export function AuditDetail({
data={data}
tab={tab}
onTabChange={onTabChange}
+ siteBlocked={siteBlocked}
/>
)
}
diff --git a/src/client/features/audit/launch/LaunchFormCard.tsx b/src/client/features/audit/launch/LaunchFormCard.tsx
index 56f2a5b3..7eb0df42 100644
--- a/src/client/features/audit/launch/LaunchFormCard.tsx
+++ b/src/client/features/audit/launch/LaunchFormCard.tsx
@@ -16,22 +16,31 @@ import {
} from "@/client/components/ui/field";
import { Input } from "@/client/components/ui/input";
import { Switch } from "@/client/components/ui/switch";
-import { MIN_PAGES } from "@/client/features/audit/launch/types";
+import {
+ clampMaxPagesInput,
+ MIN_PAGES,
+} from "@/client/features/audit/launch/types";
import type { useLaunchController } from "@/client/features/audit/launch/useLaunchController";
import { getFieldError, getFormError } from "@/client/lib/forms";
-import { PAID_MAX_AUDIT_PAGES } from "@/shared/audit-limits";
+import { isHostedClientAuthMode } from "@/lib/auth-mode";
+import { RENDERED_MAX_AUDIT_PAGES } from "@/shared/audit-limits";
+import { renderingEstimateText } from "@/shared/audit-rendering";
import { SUBSCRIBE_ROUTE } from "@/shared/billing";
type Props = {
launchForm: ReturnType<typeof useLaunchController>["launchForm"];
commitMaxPagesInput: () => number;
maxPagesLimit: number;
+ paidMaxPagesLimit: number;
+ canRenderJavaScript?: boolean;
};
export function LaunchFormCard({
commitMaxPagesInput,
launchForm,
maxPagesLimit,
+ paidMaxPagesLimit,
+ canRenderJavaScript,
}: Props) {
return (
<Card>
@@ -88,8 +97,16 @@ export function LaunchFormCard({
launchForm={launchForm}
commitMaxPagesInput={commitMaxPagesInput}
maxPagesLimit={maxPagesLimit}
+ paidMaxPagesLimit={paidMaxPagesLimit}
/>
- <LighthouseOptions launchForm={launchForm} />
+ <div className="space-y-4">
+ <LighthouseOptions launchForm={launchForm} />
+ <RenderingOptions
+ launchForm={launchForm}
+ maxPagesLimit={maxPagesLimit}
+ canRenderJavaScript={canRenderJavaScript}
+ />
+ </div>
</div>
</form>
@@ -103,9 +120,8 @@ function LaunchOptions({
launchForm,
commitMaxPagesInput,
maxPagesLimit,
+ paidMaxPagesLimit,
}: Props) {
- const isFreeLimited = maxPagesLimit < PAID_MAX_AUDIT_PAGES;
-
return (
<Field className="rounded-lg border border-border p-3">
<FieldLabel htmlFor="audit-max-pages">Max pages</FieldLabel>
@@ -132,13 +148,16 @@ function LaunchOptions({
</launchForm.Field>
<FieldDescription>
Enter any value from {MIN_PAGES} to {maxPagesLimit.toLocaleString()}.
- {isFreeLimited ? (
+ {maxPagesLimit === RENDERED_MAX_AUDIT_PAGES
+ ? " Audits that render JavaScript are limited to this many pages."
+ : null}
+ {maxPagesLimit < paidMaxPagesLimit ? (
<>
{" "}
<Link to={SUBSCRIBE_ROUTE} search={{ upgrade: true }}>
Upgrade
</Link>{" "}
- to crawl up to {PAID_MAX_AUDIT_PAGES.toLocaleString()} pages.
+ to crawl up to {paidMaxPagesLimit.toLocaleString()} pages.
</>
) : null}
</FieldDescription>
@@ -183,6 +202,68 @@ function LighthouseOptions({ launchForm }: Pick<Props, "launchForm">) {
);
}
+function RenderingOptions({
+ launchForm,
+ maxPagesLimit,
+ canRenderJavaScript,
+}: Pick<Props, "launchForm" | "maxPagesLimit" | "canRenderJavaScript">) {
+ return (
+ <Field className="rounded-lg border border-border p-3">
+ <div className="flex items-center gap-2">
+ <launchForm.Field name="renderJavaScript">
+ {(field) => (
+ <Switch
+ id="audit-render-javascript"
+ checked={field.state.value}
+ disabled={canRenderJavaScript !== true}
+ onCheckedChange={(checked) => field.handleChange(checked)}
+ />
+ )}
+ </launchForm.Field>
+ <FieldLabel
+ htmlFor="audit-render-javascript"
+ title="Loads each page in a browser before auditing it. Slower."
+ >
+ Render JavaScript
+ </FieldLabel>
+ </div>
+
+ {isHostedClientAuthMode() && (
+ <launchForm.Subscribe
+ selector={(state) => ({
+ renderJavaScript: state.values.renderJavaScript,
+ maxPagesInput: state.values.maxPagesInput,
+ })}
+ >
+ {({ renderJavaScript, maxPagesInput }) =>
+ renderJavaScript ? (
+ <FieldDescription>
+ {renderingEstimateText(
+ clampMaxPagesInput(maxPagesInput, maxPagesLimit),
+ )}
+ </FieldDescription>
+ ) : null
+ }
+ </launchForm.Subscribe>
+ )}
+ {canRenderJavaScript === false && (
+ <FieldDescription>
+ This deployment has no browser, so rendering needs a Context.dev API
+ key. Set <code>CONTEXT_API_KEY</code>, restart OpenSEO, then reload
+ this page.{" "}
+ <a
+ href="https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md#render-javascript-in-site-audits"
+ target="_blank"
+ rel="noreferrer"
+ >
+ Setup guide
+ </a>
+ </FieldDescription>
+ )}
+ </Field>
+ );
+}
+
function LaunchErrors({ launchForm }: Pick<Props, "launchForm">) {
return (
<div className="space-y-2">
diff --git a/src/client/features/audit/launch/LaunchView.tsx b/src/client/features/audit/launch/LaunchView.tsx
index 6c1470ca..c88021d0 100644
--- a/src/client/features/audit/launch/LaunchView.tsx
+++ b/src/client/features/audit/launch/LaunchView.tsx
@@ -35,6 +35,8 @@ export function LaunchView({
launchForm={controller.launchForm}
commitMaxPagesInput={controller.commitMaxPagesInput}
maxPagesLimit={controller.maxPagesLimit}
+ paidMaxPagesLimit={controller.paidMaxPagesLimit}
+ canRenderJavaScript={controller.canRenderJavaScript}
/>
<AuditHistorySection
diff --git a/src/client/features/audit/launch/types.ts b/src/client/features/audit/launch/types.ts
index 065fe5b2..e2b89d0e 100644
--- a/src/client/features/audit/launch/types.ts
+++ b/src/client/features/audit/launch/types.ts
@@ -3,22 +3,39 @@ import {
FREE_MAX_AUDIT_PAGES,
MIN_AUDIT_PAGES,
PAID_MAX_AUDIT_PAGES,
+ RENDERED_MAX_AUDIT_PAGES,
} from "@/shared/audit-limits";
export const MIN_PAGES = MIN_AUDIT_PAGES;
-export function getMaxPagesLimit(isFreePlan: boolean) {
- return isFreePlan ? FREE_MAX_AUDIT_PAGES : PAID_MAX_AUDIT_PAGES;
+export function getMaxPagesLimit(
+ isFreePlan: boolean,
+ renderJavaScript: boolean,
+) {
+ const planLimit = isFreePlan ? FREE_MAX_AUDIT_PAGES : PAID_MAX_AUDIT_PAGES;
+ return renderJavaScript
+ ? Math.min(planLimit, RENDERED_MAX_AUDIT_PAGES)
+ : planLimit;
+}
+
+/** The page limit an audit runs with for what is typed in the form. */
+export function clampMaxPagesInput(input: string, maxPagesLimit: number) {
+ const value = input ? Number.parseInt(input, 10) : MIN_PAGES;
+ return Number.isFinite(value)
+ ? Math.max(MIN_PAGES, Math.min(maxPagesLimit, Math.round(value)))
+ : MIN_PAGES;
}
export type LaunchFormValues = {
url: string;
maxPagesInput: string;
runLighthouse: boolean;
+ renderJavaScript: boolean;
};
export const DEFAULT_LAUNCH_FORM_VALUES: LaunchFormValues = {
url: "",
maxPagesInput: String(DEFAULT_AUDIT_PAGES),
runLighthouse: false,
+ renderJavaScript: false,
};
diff --git a/src/client/features/audit/launch/useLaunchController.ts b/src/client/features/audit/launch/useLaunchController.ts
index aa0b41f2..be604e1e 100644
--- a/src/client/features/audit/launch/useLaunchController.ts
+++ b/src/client/features/audit/launch/useLaunchController.ts
@@ -1,5 +1,5 @@
import { useRef, useState } from "react";
-import { useForm } from "@tanstack/react-form";
+import { useForm, useStore } from "@tanstack/react-form";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
@@ -10,14 +10,19 @@ import {
import {
DEFAULT_LAUNCH_FORM_VALUES,
getMaxPagesLimit,
- MIN_PAGES,
+ clampMaxPagesInput,
type LaunchFormValues,
} from "@/client/features/audit/launch/types";
import {
createFormValidationErrors,
shouldValidateFieldOnChange,
} from "@/client/lib/forms";
-import { getStandardErrorMessage } from "@/client/lib/error-messages";
+import {
+ getErrorCode,
+ getStandardErrorMessage,
+} from "@/client/lib/error-messages";
+import { renderingCreditsNeededText } from "@/shared/audit-rendering";
+import { useAuditCapabilities } from "@/client/features/audit/shared";
function getLaunchValidationErrors(
value: LaunchFormValues,
@@ -49,7 +54,7 @@ export function useLaunchController({
isFreePlan: boolean;
onAuditStarted: (auditId: string) => void;
}) {
- const maxPagesLimit = getMaxPagesLimit(isFreePlan);
+ const capabilitiesQuery = useAuditCapabilities(projectId);
const historyQuery = useQuery({
queryKey: ["audit-history", projectId],
queryFn: () => getAuditHistory({ data: { projectId } }),
@@ -75,7 +80,10 @@ export function useLaunchController({
onSubmit: ({ value }) => getLaunchValidationErrors(value, true),
},
onSubmit: async ({ formApi, value }) => {
- const effectiveMaxPages = commitMaxPagesInput(launchForm, maxPagesLimit);
+ const effectiveMaxPages = commitMaxPagesInput(
+ launchForm,
+ getMaxPagesLimit(isFreePlan, value.renderJavaScript),
+ );
formApi.setErrorMap({ onSubmit: undefined });
if (effectiveMaxPages > 500 && !largeCrawlConfirmed.current) {
@@ -90,23 +98,40 @@ export function useLaunchController({
startUrl: value.url,
maxPages: effectiveMaxPages,
lighthouseStrategy: value.runLighthouse ? "auto" : "none",
+ renderJavaScript: value.renderJavaScript,
});
toast.success("Audit started!");
onAuditStarted(result.auditId);
} catch (error) {
+ // Starting an audit refuses for credits only when the rendering hold
+ // does not fit, so the form can say how much the audit needs.
+ const message =
+ value.renderJavaScript &&
+ getErrorCode(error) === "INSUFFICIENT_CREDITS"
+ ? renderingCreditsNeededText(effectiveMaxPages)
+ : getStandardErrorMessage(error, "Failed to start audit");
formApi.setErrorMap({
- onSubmit: createFormValidationErrors({
- form: getStandardErrorMessage(error, "Failed to start audit"),
- }),
+ onSubmit: createFormValidationErrors({ form: message }),
});
}
},
});
+ const renderJavaScript = useStore(
+ launchForm.store,
+ (state) => state.values.renderJavaScript,
+ );
+ const maxPagesLimit = getMaxPagesLimit(isFreePlan, renderJavaScript);
+ // What an upgrade offers with the current options, so the upgrade hint
+ // never promises pages a rendered audit cannot crawl.
+ const paidMaxPagesLimit = getMaxPagesLimit(false, renderJavaScript);
+
return {
launchForm,
historyQuery,
+ canRenderJavaScript: capabilitiesQuery.data?.canRenderJavaScript,
maxPagesLimit,
+ paidMaxPagesLimit,
commitMaxPagesInput: () => commitMaxPagesInput(launchForm, maxPagesLimit),
deleteAudit: (auditId: string) => deleteMutation.mutate(auditId),
largeCrawlPages,
@@ -133,6 +158,7 @@ function useLaunchMutations({ projectId }: { projectId: string }) {
startUrl: string;
maxPages: number;
lighthouseStrategy: "auto" | "none";
+ renderJavaScript: boolean;
}) => startAudit({ data }),
onSuccess: () => {
void invalidateHistory();
@@ -158,11 +184,10 @@ function commitMaxPagesInput(
},
maxPagesLimit: number,
) {
- const maxPagesInput = launchForm.state.values.maxPagesInput;
- const value = maxPagesInput ? Number.parseInt(maxPagesInput, 10) : MIN_PAGES;
- const safeValue = Number.isFinite(value)
- ? Math.max(MIN_PAGES, Math.min(maxPagesLimit, Math.round(value)))
- : MIN_PAGES;
+ const safeValue = clampMaxPagesInput(
+ launchForm.state.values.maxPagesInput,
+ maxPagesLimit,
+ );
launchForm.setFieldValue("maxPagesInput", String(safeValue));
return safeValue;
}
diff --git a/src/client/features/audit/results/AuditResultsTableFilterLogic.ts b/src/client/features/audit/results/AuditResultsTableFilterLogic.ts
index de97bf94..61b51842 100644
--- a/src/client/features/audit/results/AuditResultsTableFilterLogic.ts
+++ b/src/client/features/audit/results/AuditResultsTableFilterLogic.ts
@@ -1,4 +1,5 @@
import type { AuditResultsData } from "@/client/features/audit/results/types";
+import type { PageFetchClass } from "@/shared/audit-fetch-class";
export type PageRow = AuditResultsData["pages"][number];
type PerformanceResultRow = AuditResultsData["lighthouse"][number];
@@ -18,6 +19,7 @@ type LighthouseFailureFields = {
export type PagesFilters = {
query: string;
status: "all" | "ok" | "redirect" | "error" | "missing";
+ fetchClass: "all" | PageFetchClass;
minWords: string;
maxWords: string;
minResponseMs: string;
@@ -39,6 +41,7 @@ export type PerformanceFilters = {
export const EMPTY_PAGES_FILTERS: PagesFilters = {
query: "",
status: "all",
+ fetchClass: "all",
minWords: "",
maxWords: "",
minResponseMs: "",
@@ -81,6 +84,9 @@ export function filterPages(rows: PageRow[], filters: PagesFilters) {
if (!haystack.includes(query)) return false;
}
if (!matchesStatus(row.statusCode, filters.status)) return false;
+ if (filters.fetchClass !== "all" && row.fetchClass !== filters.fetchClass) {
+ return false;
+ }
if (!matchesRange(row.wordCount, filters.minWords, filters.maxWords)) {
return false;
}
diff --git a/src/client/features/audit/results/AuditResultsTableFilters.tsx b/src/client/features/audit/results/AuditResultsTableFilters.tsx
index 02ed7cd9..b03418b1 100644
--- a/src/client/features/audit/results/AuditResultsTableFilters.tsx
+++ b/src/client/features/audit/results/AuditResultsTableFilters.tsx
@@ -31,7 +31,7 @@ export function PagesFilterBar({
}) {
return (
<DataTableFilterPanel activeCount={activeFilterCount} onReset={onReset}>
- <div className="grid grid-cols-1 gap-3 lg:grid-cols-3">
+ <div className="grid grid-cols-1 gap-3 lg:grid-cols-4">
<TextFilter
label="Search"
value={filters.query}
@@ -50,6 +50,18 @@ export function PagesFilterBar({
["missing", "Missing"],
]}
/>
+ <SelectFilter
+ label="Crawl result"
+ value={filters.fetchClass}
+ onChange={(fetchClass) => onChange({ ...filters, fetchClass })}
+ options={[
+ ["all", "All"],
+ ["ok", "Read"],
+ ["error", "Failed"],
+ ["blocked", "Blocked"],
+ ["rate_limited", "Rate limited"],
+ ]}
+ />
<SelectFilter
label="Alt text"
value={filters.missingAlt}
diff --git a/src/client/features/audit/results/PagesTable.tsx b/src/client/features/audit/results/PagesTable.tsx
index e9cd547e..83a52310 100644
--- a/src/client/features/audit/results/PagesTable.tsx
+++ b/src/client/features/audit/results/PagesTable.tsx
@@ -5,6 +5,7 @@ import {
type SortingState,
} from "@tanstack/react-table";
import { ExternalLink } from "lucide-react";
+import { Badge } from "@/client/components/ui/badge";
import { DataTable, useDataTable } from "@/client/components/table/DataTable";
import { SortableHeader } from "@/client/components/table/SortableHeader";
import {
@@ -109,7 +110,19 @@ function buildPagesColumns({
}),
pageColumnHelper.accessor("statusCode", {
header: ({ column }) => <SortableHeader column={column} label="Status" />,
- cell: ({ getValue }) => <HttpStatusBadge code={getValue()} />,
+ // A failed fetch or render has no HTTP status to show.
+ cell: ({ getValue, row }) =>
+ row.original.fetchClass === "error" ? (
+ <Badge
+ variant="destructive"
+ size="sm"
+ title="Fetching or rendering failed, so this page was not checked for content issues."
+ >
+ Failed
+ </Badge>
+ ) : (
+ <HttpStatusBadge code={getValue()} />
+ ),
sortingFn: nullableNumberSort,
}),
pageColumnHelper.accessor("title", {
diff --git a/src/client/features/audit/results/RenderingWarnings.tsx b/src/client/features/audit/results/RenderingWarnings.tsx
new file mode 100644
index 00000000..a3818c8e
--- /dev/null
+++ b/src/client/features/audit/results/RenderingWarnings.tsx
@@ -0,0 +1,55 @@
+import { ShieldAlert } from "lucide-react";
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+} from "@/client/components/ui/alert";
+import type { AuditResultsData } from "@/client/features/audit/results/types";
+
+/** Report notices about JavaScript: app shells, and pages a render missed. */
+export function RenderingWarnings({ data }: { data: AuditResultsData }) {
+ const rendered = data.audit.config.renderJavaScript;
+ const hasShells = data.issues.some(
+ (issue) => issue.issueType === "javascript-rendering-suspected",
+ );
+ const unreadCount = data.pages.filter(
+ (page) => page.fetchClass === "error",
+ ).length;
+
+ return (
+ <>
+ {hasShells && (
+ <Alert variant="warning">
+ <ShieldAlert />
+ <AlertTitle>
+ Some pages may need JavaScript to show their content.
+ </AlertTitle>
+ <AlertDescription>
+ {rendered
+ ? "They were still loading after rendering, so we couldn't check them."
+ : "Turn on Render JavaScript and run the audit again to check them."}
+ </AlertDescription>
+ </Alert>
+ )}
+
+ {rendered && unreadCount > 0 && (
+ <Alert variant="warning">
+ <ShieldAlert />
+ <AlertTitle>
+ We couldn't read {unreadCount}{" "}
+ {unreadCount === 1 ? "page" : "pages"}.
+ </AlertTitle>
+ <AlertDescription>
+ To see them, open Pages and filter Crawl result by Failed.
+ </AlertDescription>
+ </Alert>
+ )}
+
+ {rendered && (
+ <p className="text-sm text-muted-foreground">
+ JavaScript rendering was enabled for this audit.
+ </p>
+ )}
+ </>
+ );
+}
diff --git a/src/client/features/audit/results/ResultsView.tsx b/src/client/features/audit/results/ResultsView.tsx
index e98cdcfc..20b71916 100644
--- a/src/client/features/audit/results/ResultsView.tsx
+++ b/src/client/features/audit/results/ResultsView.tsx
@@ -13,6 +13,7 @@ import {
} from "@/client/features/audit/results/IssuesView";
import { PagesTable } from "@/client/features/audit/results/PagesTable";
import { ShopifyCrawlWarning } from "@/client/features/audit/results/ShopifyCrawlWarning";
+import { RenderingWarnings } from "@/client/features/audit/results/RenderingWarnings";
import { PerformanceTable } from "@/client/features/audit/results/ResultsTables";
import {
BotProtectionAdvice,
@@ -36,11 +37,14 @@ export function ResultsView({
data,
onTabChange,
tab,
+ siteBlocked,
}: {
projectId: string;
data: AuditResultsData;
tab: string;
onTabChange: (tab: ResultsTab) => void;
+ /** The page already says bot protection blocked the whole site. */
+ siteBlocked: boolean;
}) {
const { audit, pages, lighthouse, issues } = data;
const crawlStopped = issues.some(
@@ -93,16 +97,18 @@ export function ResultsView({
<ShopifyCrawlWarning projectId={projectId} audit={audit} />
)}
- {!shopifyLimited && blockedCount > 0 && (
+ {!shopifyLimited && !siteBlocked && blockedCount > 0 && (
<Alert variant="warning">
<ShieldAlert />
<AlertTitle>
- We were blocked on {blockedCount}{" "}
+ Bot protection blocked our crawler on {blockedCount}{" "}
{blockedCount === 1 ? "page" : "pages"}.
</AlertTitle>
<AlertDescription>
- The site's bot protection challenged our crawler, so those pages
- couldn't be audited. <BotProtectionAdvice />
+ <BotProtectionAdvice
+ projectId={projectId}
+ rendered={audit.config.renderJavaScript === true}
+ />
</AlertDescription>
</Alert>
)}
@@ -125,6 +131,8 @@ export function ResultsView({
</Alert>
)}
+ <RenderingWarnings data={data} />
+
<StatsStrip
pagesCrawled={audit.pagesCrawled}
issues={issues}
diff --git a/src/client/features/audit/results/ShopifyCrawlWarning.tsx b/src/client/features/audit/results/ShopifyCrawlWarning.tsx
index 323ba6e4..6a386dff 100644
--- a/src/client/features/audit/results/ShopifyCrawlWarning.tsx
+++ b/src/client/features/audit/results/ShopifyCrawlWarning.tsx
@@ -76,6 +76,7 @@ export function ShopifyCrawlWarning({
startUrl: audit.startUrl,
maxPages: audit.config.maxPages,
lighthouseStrategy: audit.config.lighthouseStrategy,
+ renderJavaScript: audit.config.renderJavaScript,
},
}),
onSuccess: (result) => {
diff --git a/src/client/features/audit/shared.tsx b/src/client/features/audit/shared.tsx
index 2a93a055..177caf33 100644
--- a/src/client/features/audit/shared.tsx
+++ b/src/client/features/audit/shared.tsx
@@ -1,4 +1,5 @@
import type { ReactNode } from "react";
+import { useQuery } from "@tanstack/react-query";
import {
AlertCircle,
CheckCircle,
@@ -10,6 +11,7 @@ import {
import { cn } from "cn";
import { Badge } from "@/client/components/ui/badge";
import { Spinner } from "@/client/components/ui/spinner";
+import { getAuditCapabilities } from "@/serverFunctions/audit";
import type { IssueSeverity } from "@/shared/audit-issues";
export function extractPathname(url: string): string {
@@ -136,12 +138,27 @@ export function SeverityBadge({
);
}
-/** Advice for a site whose bot protection blocked the crawler. */
-export function BotProtectionAdvice() {
- return (
+/** Whether this deployment can render JavaScript in site audits. */
+export function useAuditCapabilities(projectId: string) {
+ return useQuery({
+ queryKey: ["audit-capabilities", projectId],
+ queryFn: () => getAuditCapabilities({ data: { projectId } }),
+ });
+}
+
+/** What to do when a site's bot protection blocked the crawler. */
+export function BotProtectionAdvice({
+ projectId,
+ rendered,
+}: {
+ projectId: string;
+ /** Whether this audit already rendered JavaScript. */
+ rendered: boolean;
+}) {
+ const canRender =
+ useAuditCapabilities(projectId).data?.canRenderJavaScript === true;
+ const desktopCrawlers = (
<>
- We don't have a workaround for this yet. Desktop crawlers run from your
- own machine and usually get past it: try{" "}
<a
href="https://github.com/PhialsBasement/LibreCrawl"
target="_blank"
@@ -149,15 +166,29 @@ export function BotProtectionAdvice() {
>
LibreCrawl
</a>{" "}
- (free, open source) or{" "}
+ or{" "}
<a
href="https://www.screamingfrog.co.uk/seo-spider/"
target="_blank"
rel="noreferrer"
>
Screaming Frog
- </a>{" "}
- (free up to 500 URLs).
+ </a>
+ </>
+ );
+
+ if (!rendered && canRender) {
+ return (
+ <>
+ Turn on Render JavaScript and run the audit again. To avoid the extra
+ cost, use a free desktop crawler like {desktopCrawlers}.
+ </>
+ );
+ }
+ return (
+ <>
+ {rendered ? "Rendering couldn't get past it. " : null}
+ Try a free desktop crawler like {desktopCrawlers}.
</>
);
}
diff --git a/src/env.d.ts b/src/env.d.ts
index 8816c0bf..1fbbe1d8 100644
--- a/src/env.d.ts
+++ b/src/env.d.ts
@@ -4,6 +4,13 @@
declare namespace Cloudflare {
interface Env {
R2: R2Bucket;
+ // Browser Run binding for site-audit JavaScript rendering, audit worker
+ // only. Inline import preserves the ambient Env augmentation.
+ // oxlint-disable-next-line typescript-eslint/consistent-type-imports
+ BROWSER?: import("@cloudflare/workers-types").BrowserRun;
+ // Context.dev key: the rendering fallback when Browser Run fails or is
+ // blocked, and the only renderer on Docker.
+ CONTEXT_API_KEY?: string;
OAUTH_KV: KVNamespace;
// Durable Object backing the SAM in-app agent (see wrangler.jsonc).
diff --git a/src/lib/selfhost-preflight.ts b/src/lib/selfhost-preflight.ts
index eb0555e6..d187a934 100644
--- a/src/lib/selfhost-preflight.ts
+++ b/src/lib/selfhost-preflight.ts
@@ -14,7 +14,7 @@ type PreflightLevel = "ok" | "info" | "warn" | "fail";
type PreflightItem = {
// Stable identifier shared with /api/health's check map.
- key: "auth" | "dataforseo" | "gsc" | "ai" | "runtime";
+ key: "auth" | "dataforseo" | "gsc" | "ai" | "rendering" | "runtime";
name: string;
level: PreflightLevel;
message: string;
@@ -211,6 +211,23 @@ function checkOptionalFeatures(env: EnvRecord, items: PreflightItem[]): void {
"OPENROUTER_API_KEY not set (optional) — SAM, the in-app SEO agent, is disabled.",
},
);
+
+ items.push(
+ get(env, "CONTEXT_API_KEY")
+ ? {
+ key: "rendering",
+ name: "JavaScript rendering",
+ level: "ok",
+ message: "CONTEXT_API_KEY set",
+ }
+ : {
+ key: "rendering",
+ name: "JavaScript rendering",
+ level: "info",
+ message:
+ 'CONTEXT_API_KEY not set (optional) — on Docker the site audit "Render JavaScript" option is disabled; on Cloudflare, Browser Run renders without a fallback.',
+ },
+ );
}
// Shared per-feature checks: the Docker preflight prints these at boot and
diff --git a/src/server/billing/subscription.ts b/src/server/billing/subscription.ts
index 2457da13..2fc98303 100644
--- a/src/server/billing/subscription.ts
+++ b/src/server/billing/subscription.ts
@@ -100,7 +100,7 @@ export async function customerHasManagedAccess(customerId: string) {
// Remaining shared usage credits — the monthly `usage_credits` balance plus the
// rolled-over `topup_credits` balance. Both DataForSEO and LLM spend draw from
// these (the `seo_data_usage` and `llm_usage` features both map into them).
-async function getUsageCreditsRemaining(customerId: string): Promise<{
+export async function getUsageCreditsRemaining(customerId: string): Promise<{
monthlyRemaining: number;
topupRemaining: number;
}> {
@@ -209,11 +209,11 @@ export async function checkUsageCreditsDepleted(
// death between check and finalize) releases at this TTL with no deduction.
const HOLD_TTL_MS = 30 * 60_000;
-type UsageCreditFeatureId =
+export type UsageCreditFeatureId =
| typeof AUTUMN_SEO_DATA_BALANCE_FEATURE_ID
| typeof AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID;
-type UsageCreditHold = {
+export type UsageCreditHold = {
lockId: string;
featureId: UsageCreditFeatureId;
estimatedCredits: number;
@@ -237,14 +237,26 @@ type UsageCreditHold = {
* absent feature reads `allowed: false, balance: null` and is a genuine
* refusal.
*/
-async function holdCredits(
- customerId: string,
- featureId: UsageCreditFeatureId,
- estimatedCredits: number,
- callIndexes: readonly number[],
- properties: Record<string, unknown>,
-) {
- const lockId = `dfs_${customerId}_${crypto.randomUUID()}`;
+export async function holdCredits(args: {
+ customerId: string;
+ featureId: UsageCreditFeatureId;
+ estimatedCredits: number;
+ callIndexes: readonly number[];
+ properties: Record<string, unknown>;
+ // A site audit's rendering hold must outlive the whole crawl, not one call.
+ ttlMs?: number;
+ lockPrefix?: string;
+}) {
+ const {
+ customerId,
+ featureId,
+ estimatedCredits,
+ callIndexes,
+ properties,
+ ttlMs = HOLD_TTL_MS,
+ lockPrefix = "dfs",
+ } = args;
+ const lockId = `${lockPrefix}_${customerId}_${crypto.randomUUID()}`;
const hold: UsageCreditHold = {
lockId,
featureId,
@@ -259,7 +271,7 @@ async function holdCredits(
requiredBalance: estimatedCredits,
sendEvent: true,
properties,
- lock: { lockId, enabled: true, expiresAt: Date.now() + HOLD_TTL_MS },
+ lock: { lockId, enabled: true, expiresAt: Date.now() + ttlMs },
},
AUTUMN_TRACK_RETRY_OPTIONS,
);
@@ -326,13 +338,13 @@ export async function reserveUsageCredits(args: {
credits += callCredits[index];
}
if (fitting.length === 0) return null;
- return holdCredits(
- args.customerId,
+ return holdCredits({
+ customerId: args.customerId,
featureId,
- credits,
- fitting,
+ estimatedCredits: credits,
+ callIndexes: fitting,
properties,
- );
+ });
};
const holds: UsageCreditHold[] = [];
@@ -415,6 +427,48 @@ function errorBodyIncludes(error: unknown, text: string) {
);
}
+/**
+ * Confirms `credits` against a hold (Autumn deducts that amount, above or
+ * below the hold, and returns the rest), or releases the hold when `credits`
+ * is 0. Retries once. `landed: false` means the deduction may be lost; the
+ * hold then expires at its TTL.
+ */
+export async function finalizeHold(
+ hold: UsageCreditHold,
+ credits: number,
+ properties: Record<string, unknown>,
+): Promise<{ landed: boolean; error?: unknown }> {
+ // No SDK-level 5xx retry (AUTUMN_TRACK_RETRY_OPTIONS): this loop owns
+ // the retry so a "Lock not found" can only be seen on our second attempt.
+ const finalize = () =>
+ autumn.balances.finalize(
+ {
+ lockId: hold.lockId,
+ ...(credits > 0
+ ? { action: "confirm", overrideValue: credits }
+ : { action: "release" }),
+ properties,
+ },
+ AUTUMN_TRACK_RETRY_OPTIONS,
+ );
+
+ let lastError: unknown;
+ for (const attempt of [1, 2]) {
+ if (attempt === 2) await sleep(250);
+ try {
+ if ((await finalize()).success) return { landed: true };
+ } catch (error) {
+ lastError = error;
+ if (errorBodyIncludes(error, "Lock not found")) {
+ // On the retry this means the first attempt landed; on the first
+ // attempt the hold has already expired and the deduction is lost.
+ return attempt === 2 ? { landed: true } : { landed: false, error };
+ }
+ }
+ }
+ return { landed: false, error: lastError };
+}
+
/**
* Settles a hold on the provider's real cost: confirms the deduction at the
* actual credits (Autumn deducts the override, above or below the hold, and
@@ -442,50 +496,20 @@ export async function settleUsageCredits(args: {
}
const paths = [...new Set(costs.map((cost) => cost.path.join("/")))];
- // No SDK-level 5xx retry (AUTUMN_TRACK_RETRY_OPTIONS): this loop owns
- // the retry so a "Lock not found" can only be seen on our second attempt.
- const finalize = () =>
- autumn.balances.finalize(
- {
- lockId: hold.lockId,
- ...(actualCredits > 0
- ? { action: "confirm", overrideValue: actualCredits }
- : { action: "release" }),
- properties: {
- creditFeature,
- provider: "dataforseo",
- paths,
- totalCostUsd,
- estimatedCredits: hold.estimatedCredits,
- },
- },
- AUTUMN_TRACK_RETRY_OPTIONS,
- );
-
- let landed = false;
- let lastError: unknown;
- for (const attempt of [1, 2]) {
- if (attempt === 2) await sleep(250);
- try {
- landed = (await finalize()).success;
- } catch (error) {
- lastError = error;
- if (errorBodyIncludes(error, "Lock not found")) {
- // On the retry this means the first attempt landed; on the first
- // attempt the hold has already expired and the deduction is lost.
- landed = attempt === 2;
- break;
- }
- }
- if (landed) break;
- }
+ const { landed, error } = await finalizeHold(hold, actualCredits, {
+ creditFeature,
+ provider: "dataforseo",
+ paths,
+ totalCostUsd,
+ estimatedCredits: hold.estimatedCredits,
+ });
if (!landed) {
console.error("[autumn] finalize failed", {
organizationId: customer.organizationId,
lockId: hold.lockId,
held: hold.estimatedCredits,
actual: actualCredits,
- error: lastError,
+ error,
});
return;
}
diff --git a/src/server/features/audit/services/AuditService.rendering.test.ts b/src/server/features/audit/services/AuditService.rendering.test.ts
new file mode 100644
index 00000000..2a3e1cd2
--- /dev/null
+++ b/src/server/features/audit/services/AuditService.rendering.test.ts
@@ -0,0 +1,127 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ workflowCreate:
+ vi.fn<(options: { params: { renderLocks?: unknown } }) => Promise<void>>(),
+ deleteAudit: vi.fn(),
+ renderingAllowed: vi.fn(),
+ lock: vi.fn(),
+ release: vi.fn(),
+}));
+
+vi.mock("cloudflare:workers", () => ({
+ env: {
+ SITE_AUDIT_WORKFLOW: {
+ create: mocks.workflowCreate,
+ get: vi.fn().mockRejectedValue(new Error("No instance")),
+ },
+ },
+}));
+vi.mock("@/server/lib/audit/rendering-policy", () => ({
+ isAuditRenderingAllowed: mocks.renderingAllowed,
+}));
+vi.mock("@/server/lib/audit/rendering-billing", () => ({
+ lockRenderingCredits: mocks.lock,
+ releaseRenderingLocks: mocks.release,
+}));
+vi.mock("@/server/lib/audit/url-policy", () => ({
+ normalizeAndValidateStartUrl: async (url: string) => url,
+ resolveStartUrlRedirects: async (url: string) => ({ url }),
+}));
+vi.mock("@/server/features/audit/services/CrawlerCredentialService", () => ({
+ CrawlerCredentialService: {
+ resolveCrawlerAccess: vi.fn().mockResolvedValue(null),
+ openCrawlerAccess: vi.fn().mockResolvedValue(null),
+ },
+}));
+vi.mock("@/server/features/audit/repositories/AuditRepository", () => ({
+ AuditRepository: {
+ createAudit: vi.fn(),
+ getAuditUsageForOrganization: vi
+ .fn()
+ .mockResolvedValue({ runningCount: 1, capacityUnits: 0 }),
+ deleteAuditForProject: mocks.deleteAudit,
+ },
+}));
+vi.mock("@/server/billing/subscription", () => ({}));
+vi.mock("@/server/features/audit/AuditScratchpad", () => ({}));
+vi.mock("@/server/lib/audit/progress-kv", () => ({ AuditProgressKV: {} }));
+
+import { AuditService } from "@/server/features/audit/services/AuditService";
+import { AppError } from "@/server/lib/errors";
+
+const locks = [
+ {
+ lockId: "lock",
+ featureId: "usage_credits" as const,
+ estimatedCredits: 384,
+ },
+];
+const renderedAudit = {
+ actorUserId: "user-1",
+ billingCustomer: {
+ userId: "user-1",
+ userEmail: "[email protected]",
+ organizationId: "org-1",
+ },
+ projectId: "project-1",
+ startUrl: "https://example.com/",
+ maxPages: 100,
+ renderJavaScript: true,
+ limitTier: "paid" as const,
+};
+
+describe("rendered audit start", () => {
+ beforeEach(() => {
+ mocks.renderingAllowed.mockResolvedValue(true);
+ mocks.lock.mockResolvedValue(locks);
+ });
+
+ it("rejects rendering where the deployment cannot provide it, saying why", async () => {
+ mocks.renderingAllowed.mockResolvedValue(false);
+ const error = await AuditService.startAudit(renderedAudit).catch(
+ (reason: unknown) => reason,
+ );
+ expect(error).toMatchObject({ code: "FORBIDDEN" });
+ // MCP clients see this message as the tool's answer.
+ expect(String(error)).toContain("CONTEXT_API_KEY");
+ expect(mocks.lock).not.toHaveBeenCalled();
+ });
+
+ it("holds the audit's worst case and hands the locks to the workflow", async () => {
+ await AuditService.startAudit(renderedAudit);
+ expect(mocks.lock).toHaveBeenCalledWith(
+ expect.objectContaining({ maxPages: 100 }),
+ );
+ expect(mocks.workflowCreate.mock.calls[0][0].params.renderLocks).toEqual(
+ locks,
+ );
+ });
+
+ it("refuses more than 1,000 rendered pages on a paid plan before holding credits", async () => {
+ const error = await AuditService.startAudit({
+ ...renderedAudit,
+ maxPages: 1_001,
+ }).catch((reason: unknown) => reason);
+ expect(error).toMatchObject({ code: "AUDIT_PAGE_LIMIT_EXCEEDED" });
+ expect(String(error)).toContain("limited to 1,000 pages");
+ expect(mocks.lock).not.toHaveBeenCalled();
+ });
+
+ it("does not start an audit the organization cannot cover", async () => {
+ mocks.lock.mockRejectedValue(new AppError("INSUFFICIENT_CREDITS"));
+ await expect(AuditService.startAudit(renderedAudit)).rejects.toMatchObject({
+ code: "INSUFFICIENT_CREDITS",
+ });
+ expect(mocks.workflowCreate).not.toHaveBeenCalled();
+ expect(mocks.deleteAudit).toHaveBeenCalled();
+ });
+
+ it("returns the hold when the workflow cannot start", async () => {
+ mocks.workflowCreate.mockRejectedValue(new Error("Workflow unavailable"));
+ await expect(AuditService.startAudit(renderedAudit)).rejects.toThrow(
+ "Workflow unavailable",
+ );
+ expect(mocks.release).toHaveBeenCalledWith(locks);
+ });
+});
diff --git a/src/server/features/audit/services/AuditService.ts b/src/server/features/audit/services/AuditService.ts
index 9987c9e4..fa86e717 100644
--- a/src/server/features/audit/services/AuditService.ts
+++ b/src/server/features/audit/services/AuditService.ts
@@ -1,3 +1,9 @@
+import { isAuditRenderingAllowed } from "@/server/lib/audit/rendering-policy";
+import {
+ lockRenderingCredits,
+ releaseRenderingLocks,
+ type RenderingLock,
+} from "@/server/lib/audit/rendering-billing";
import { env } from "cloudflare:workers";
import {
customerHasManagedAccess,
@@ -14,6 +20,7 @@ import {
type AuditLimitTier,
} from "@/server/features/audit/services/audit-capacity";
import { AppError } from "@/server/lib/errors";
+import { RENDERED_MAX_AUDIT_PAGES } from "@/shared/audit-limits";
import { AuditProgressKV } from "@/server/lib/audit/progress-kv";
import {
parseAuditConfig,
@@ -56,12 +63,26 @@ async function startAudit(input: {
maxPages?: number;
lighthouseStrategy?: LighthouseStrategy;
limitTier: AuditLimitTier;
+ renderJavaScript?: boolean;
}) {
+ const renderJavaScript = input.renderJavaScript ?? false;
+ if (renderJavaScript && !(await isAuditRenderingAllowed())) {
+ throw new AppError(
+ "FORBIDDEN",
+ "JavaScript rendering is not available on this deployment. It needs a Cloudflare deployment with Browser Run, or CONTEXT_API_KEY. Run the audit without rendering instead.",
+ );
+ }
const limits = AUDIT_LIMITS[input.limitTier];
const maxPages = clampAuditMaxPages(input.maxPages);
if (maxPages > limits.maxPagesPerAudit) {
throw new AppError("AUDIT_PAGE_LIMIT_EXCEEDED");
}
+ if (renderJavaScript && maxPages > RENDERED_MAX_AUDIT_PAGES) {
+ throw new AppError(
+ "AUDIT_PAGE_LIMIT_EXCEEDED",
+ `Audits that render JavaScript are limited to ${RENDERED_MAX_AUDIT_PAGES.toLocaleString("en-US")} pages.`,
+ );
+ }
const lighthouseStrategy = input.lighthouseStrategy ?? "auto";
const reservation = getEstimatedAuditCapacity({
@@ -98,6 +119,7 @@ async function startAudit(input: {
const config: AuditConfig = {
maxPages,
lighthouseStrategy,
+ renderJavaScript,
// Shopify storefronts answer with `powered-by: Shopify`; knowing this is
// what lets the report explain a throttled crawl instead of shrugging.
sitePlatform: probe.poweredBy?.toLowerCase().includes("shopify")
@@ -117,6 +139,7 @@ async function startAudit(input: {
lighthouseTotal: reservation.lighthouseTotal,
});
+ let renderLocks: RenderingLock[] = [];
try {
// Concurrency and capacity are enforced after the insert, not before: a
// pre-insert read is a check-then-act race, so parallel requests would all
@@ -134,6 +157,15 @@ async function startAudit(input: {
if (usage.capacityUnits > limits.maxCapacityUnits) {
throw new AppError("AUDIT_CAPACITY_REACHED");
}
+ // Holds the worst-case rendering cost for the whole audit. Refused here,
+ // the audit never runs; the workflow settles the hold when it ends.
+ if (renderJavaScript) {
+ renderLocks = await lockRenderingCredits({
+ customer: input.billingCustomer,
+ auditId,
+ maxPages,
+ });
+ }
await env.SITE_AUDIT_WORKFLOW.create({
id: auditId,
@@ -149,6 +181,7 @@ async function startAudit(input: {
startUrl,
config,
access: credential?.sealed,
+ renderLocks,
},
});
} catch (error) {
@@ -158,6 +191,7 @@ async function startAudit(input: {
} catch {
// The workflow may never have been created, or may already be gone.
}
+ await releaseRenderingLocks(renderLocks);
await AuditRepository.deleteAuditForProject(auditId, input.projectId);
throw error;
diff --git a/src/server/lib/audit/classify-fetch.ts b/src/server/lib/audit/classify-fetch.ts
new file mode 100644
index 00000000..772f435a
--- /dev/null
+++ b/src/server/lib/audit/classify-fetch.ts
@@ -0,0 +1,37 @@
+import type { PageFetchClass } from "@/shared/audit-fetch-class";
+
+// Bot protection that answers 2xx with a challenge in place of the page:
+// Cloudflare's interstitial, and SiteGround's sgcaptcha redirect (a 202).
+const CHALLENGE_2XX =
+ /<title>\s*(?:just a moment\.\.\.|attention required! \| cloudflare)\s*<\/title>|\/\.well-known\/sgcaptcha\//i;
+
+const CHALLENGE_BODY_MARKERS = [
+ "just a moment...",
+ "challenge-platform",
+ "cf-browser-verification",
+ "attention required! | cloudflare",
+ "verifying you are human",
+];
+
+export function classifyFetch(
+ statusCode: number,
+ mitigated: boolean,
+ bodySnippet: string,
+): PageFetchClass {
+ if (statusCode === 0) return "error";
+ // A final 429 means rate limiting, whether retries were exhausted or the
+ // requested cooldown exceeded the crawl budget. Checked before
+ // cf-mitigated: a Cloudflare rate-limiting rule sets that header too.
+ if (statusCode === 429) return "rate_limited";
+ if (mitigated) return "blocked";
+ if (statusCode === 401 || statusCode === 403) return "blocked";
+ if (statusCode >= 200 && statusCode < 300 && CHALLENGE_2XX.test(bodySnippet))
+ return "blocked";
+ if (statusCode === 503) {
+ const snippet = bodySnippet.toLowerCase();
+ if (CHALLENGE_BODY_MARKERS.some((marker) => snippet.includes(marker))) {
+ return "blocked";
+ }
+ }
+ return "ok";
+}
diff --git a/src/server/lib/audit/html-response.ts b/src/server/lib/audit/html-response.ts
new file mode 100644
index 00000000..e74ba587
--- /dev/null
+++ b/src/server/lib/audit/html-response.ts
@@ -0,0 +1,49 @@
+import type { Response as BrowserResponse } from "@cloudflare/workers-types";
+
+export const MAX_HTML_BYTES = 1024 * 1024;
+
+export async function readTextUpTo(
+ response: Response | BrowserResponse,
+ maxBytes: number,
+) {
+ if (!response.body) return "";
+
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ const parts: string[] = [];
+ let bytesRead = 0;
+
+ try {
+ while (bytesRead < maxBytes) {
+ const result = await reader.read();
+ if (result.done) break;
+ const value: unknown = result.value;
+ if (!(value instanceof Uint8Array))
+ throw new Error("Expected response bytes");
+
+ const remaining = maxBytes - bytesRead;
+ const chunk =
+ value.byteLength > remaining ? value.subarray(0, remaining) : value;
+ bytesRead += chunk.byteLength;
+ parts.push(decoder.decode(chunk, { stream: true }));
+
+ if (bytesRead >= maxBytes) {
+ await reader.cancel();
+ break;
+ }
+ }
+ } finally {
+ reader.releaseLock();
+ }
+
+ parts.push(decoder.decode());
+ return parts.join("");
+}
+
+/** The first `maxBytes` of `text` as UTF-8, as readTextUpTo keeps from a body. */
+export function truncateToBytes(text: string, maxBytes: number) {
+ const bytes = new TextEncoder().encode(text);
+ return bytes.length <= maxBytes
+ ? text
+ : new TextDecoder().decode(bytes.subarray(0, maxBytes));
+}
diff --git a/src/server/lib/audit/issues/multipage.test.ts b/src/server/lib/audit/issues/multipage.test.ts
new file mode 100644
index 00000000..96e99738
--- /dev/null
+++ b/src/server/lib/audit/issues/multipage.test.ts
@@ -0,0 +1,60 @@
+import { readFileSync } from "node:fs";
+import { createClient } from "@libsql/client";
+import { drizzle } from "drizzle-orm/libsql";
+import { afterAll, beforeAll, expect, it, vi } from "vitest";
+import type * as MultipageModule from "./multipage";
+
+vi.mock("cloudflare:workers", () => ({ env: { DATABASE_PROVIDER: "d1" } }));
+
+const client = createClient({ url: "file::memory:" });
+let runMultipageChecks: typeof MultipageModule.runMultipageChecks;
+
+beforeAll(async () => {
+ vi.doMock("@/db", () => ({ db: drizzle(client) }));
+ await client.execute("CREATE TABLE audits (id text PRIMARY KEY)");
+ // Real audit DDL keeps this query test aligned with the persisted columns.
+ for (const migration of ["0000_fantastic_vanisher", "0030_legal_reaper"]) {
+ for (const statement of readFileSync(
+ `drizzle/sqlite/${migration}.sql`,
+ "utf8",
+ ).split("--> statement-breakpoint")) {
+ if (
+ /^\s*(CREATE TABLE|ALTER TABLE) `audit_(pages|issues)`/.test(statement)
+ ) {
+ await client.execute(statement);
+ }
+ }
+ }
+ ({ runMultipageChecks } = await import("./multipage"));
+});
+afterAll(() => client.close());
+
+it("skips persisted app-shell coverage gaps while retaining genuine duplicate pages", async () => {
+ await client.execute("INSERT INTO audits (id) VALUES ('audit')");
+ for (const id of ["shell-1", "shell-2", "readable-1", "readable-2"]) {
+ await client.execute({
+ sql: "INSERT INTO audit_pages (id, audit_id, url, status_code, fetch_class, title, meta_description, word_count, content_hash) VALUES (?, 'audit', ?, 200, 'ok', ?, ?, 1, ?)",
+ args: [
+ id,
+ `https://example.com/${id}`,
+ id.startsWith("shell") ? "App shell" : "Real title",
+ "Shared description",
+ "same-text",
+ ],
+ });
+ }
+ for (const id of ["shell-1", "shell-2"]) {
+ await client.execute({
+ sql: "INSERT INTO audit_issues (id, audit_id, page_id, page_url, issue_type, severity) VALUES (?, 'audit', ?, ?, 'javascript-rendering-suspected', 'warning')",
+ args: [`issue-${id}`, id, `https://example.com/${id}`],
+ });
+ }
+ const { issues, hasUnreadShells } = await runMultipageChecks({
+ auditId: "audit",
+ });
+ expect(hasUnreadShells).toBe(true);
+ expect(issues).toHaveLength(6);
+ expect(new Set(issues.map((issue) => issue.pageId))).toEqual(
+ new Set(["readable-1", "readable-2"]),
+ );
+});
diff --git a/src/server/lib/audit/issues/multipage.ts b/src/server/lib/audit/issues/multipage.ts
index c5553fcb..130bcc0f 100644
--- a/src/server/lib/audit/issues/multipage.ts
+++ b/src/server/lib/audit/issues/multipage.ts
@@ -1,42 +1,62 @@
/**
- * Cross-page (multipage) issue checks over the app DB's page rows:
- * duplicates and redirect chains/loops. Pure set-queries over crawl data —
- * no fetching, no DOM.
+ * Cross-page checks that need the whole crawl: duplicate titles, meta
+ * descriptions and content, plus redirect chains and loops.
*
- * The two link-edge checks (broken-internal-link, orphan-page) live in the
+ * Reads the audit's persisted page rows from the app DB. Link-graph checks
+ * (broken links, orphan pages) are not here: they run inside the
* audit's scratchpad Durable Object (AuditScratchpad.runFinalizeChecks),
* next to the link edges themselves — link rows never touch the app DB.
*/
-import { eq } from "drizzle-orm";
+import { and, eq } from "drizzle-orm";
import { db } from "@/db";
-import { auditPages } from "@/db/schema";
+import { auditIssues, auditPages } from "@/db/schema";
import {
findDuplicates,
findRedirectChainsAndLoops,
type SlimPage,
-} from "@/server/lib/audit/issues/multipage-checks";
+} from "./multipage-checks";
import type { DetectedIssue } from "@/server/lib/audit/issues/page-reporters";
export async function runMultipageChecks(input: {
auditId: string;
-}): Promise<DetectedIssue[]> {
- const pages: SlimPage[] = await db
- .select({
- id: auditPages.id,
- url: auditPages.url,
- statusCode: auditPages.statusCode,
- fetchClass: auditPages.fetchClass,
- title: auditPages.title,
- metaDescription: auditPages.metaDescription,
- contentHash: auditPages.contentHash,
- redirectUrl: auditPages.redirectUrl,
- wordCount: auditPages.wordCount,
- isIndexable: auditPages.isIndexable,
- canonicalUrl: auditPages.canonicalUrl,
- headerCanonicalUrl: auditPages.headerCanonicalUrl,
- })
- .from(auditPages)
- .where(eq(auditPages.auditId, input.auditId));
+}): Promise<{ issues: DetectedIssue[]; hasUnreadShells: boolean }> {
+ // Unrendered app shells carry a persisted coverage warning. Their
+ // placeholder titles and loading text must not become duplicate findings.
+ const shellPageIds = new Set(
+ (
+ await db
+ .select({ pageId: auditIssues.pageId })
+ .from(auditIssues)
+ .where(
+ and(
+ eq(auditIssues.auditId, input.auditId),
+ eq(auditIssues.issueType, "javascript-rendering-suspected"),
+ ),
+ )
+ ).map((row) => row.pageId),
+ );
+ const pages: SlimPage[] = (
+ await db
+ .select({
+ id: auditPages.id,
+ url: auditPages.url,
+ statusCode: auditPages.statusCode,
+ fetchClass: auditPages.fetchClass,
+ redirectUrl: auditPages.redirectUrl,
+ title: auditPages.title,
+ metaDescription: auditPages.metaDescription,
+ contentHash: auditPages.contentHash,
+ wordCount: auditPages.wordCount,
+ isIndexable: auditPages.isIndexable,
+ canonicalUrl: auditPages.canonicalUrl,
+ headerCanonicalUrl: auditPages.headerCanonicalUrl,
+ })
+ .from(auditPages)
+ .where(eq(auditPages.auditId, input.auditId))
+ ).filter((page) => !shellPageIds.has(page.id));
- return [...findDuplicates(pages), ...findRedirectChainsAndLoops(pages)];
+ return {
+ issues: [...findDuplicates(pages), ...findRedirectChainsAndLoops(pages)],
+ hasUnreadShells: shellPageIds.size > 0,
+ };
}
diff --git a/src/server/lib/audit/issues/page-reporters.test.ts b/src/server/lib/audit/issues/page-reporters.test.ts
index 6405759d..3ea5a48d 100644
--- a/src/server/lib/audit/issues/page-reporters.test.ts
+++ b/src/server/lib/audit/issues/page-reporters.test.ts
@@ -62,6 +62,33 @@ function issueTypes(page: CrawledPageResult): string[] {
}
describe("runPageReporters", () => {
+ it("keeps known signals on an unread shell without inventing missing-content issues", () => {
+ const types = issueTypes(
+ makePage({
+ javascriptShell: true,
+ title: "",
+ metaDescription: "",
+ h1Count: 0,
+ wordCount: 1,
+ links: [],
+ isIndexable: false,
+ robotsMeta: "noindex",
+ canonicalUrl: "https://example.com/canonical",
+ headerCanonicalUrl: "https://example.com/header-canonical",
+ responseTimeMs: 2000,
+ crawlDepth: 5,
+ }),
+ );
+ expect(types).toEqual([
+ "slow-response",
+ "noindex-page",
+ "canonical-conflict",
+ "canonicalized-page",
+ "deep-page",
+ "javascript-rendering-suspected",
+ ]);
+ });
+
it("reports nothing for a healthy page", () => {
expect(issueTypes(makePage({}))).toEqual([]);
});
diff --git a/src/server/lib/audit/issues/page-reporters.ts b/src/server/lib/audit/issues/page-reporters.ts
index 4c109732..50df6197 100644
--- a/src/server/lib/audit/issues/page-reporters.ts
+++ b/src/server/lib/audit/issues/page-reporters.ts
@@ -76,11 +76,44 @@ export function runPageReporters(page: CrawledPageResult): DetectedIssue[] {
}
// Content checks only make sense for analyzed HTML documents (a PDF has no
- // title tag to miss; an empty-shell HTML page very much does).
+ // title tag to miss).
if (!page.isHtml) {
return issues;
}
+ // Indexability + canonical signals
+ if (!page.isIndexable) {
+ report("noindex-page", {
+ robotsMeta: page.robotsMeta,
+ xRobotsTag: page.xRobotsTag,
+ });
+ }
+ if (
+ page.canonicalUrl &&
+ page.headerCanonicalUrl &&
+ page.canonicalUrl !== page.headerCanonicalUrl
+ ) {
+ report("canonical-conflict", {
+ htmlCanonical: page.canonicalUrl,
+ headerCanonical: page.headerCanonicalUrl,
+ });
+ }
+ const effectiveCanonical = page.canonicalUrl ?? page.headerCanonicalUrl;
+ if (effectiveCanonical && effectiveCanonical !== page.url) {
+ report("canonicalized-page", { canonicalUrl: effectiveCanonical });
+ }
+
+ if (page.crawlDepth !== null && page.crawlDepth >= DEEP_PAGE_DEPTH) {
+ report("deep-page", { crawlDepth: page.crawlDepth });
+ }
+
+ // The initial app shell cannot establish what the rendered page is missing.
+ // Report the coverage gap instead of thin-content/missing-heading claims.
+ if (page.javascriptShell) {
+ report("javascript-rendering-suspected", { wordCount: page.wordCount });
+ return issues;
+ }
+
// Titles
if (!page.title) {
report("missing-title");
@@ -113,28 +146,6 @@ export function runPageReporters(page: CrawledPageResult): DetectedIssue[] {
report("heading-order-skip");
}
- // Indexability + canonical signals
- if (!page.isIndexable) {
- report("noindex-page", {
- robotsMeta: page.robotsMeta,
- xRobotsTag: page.xRobotsTag,
- });
- }
- if (
- page.canonicalUrl &&
- page.headerCanonicalUrl &&
- page.canonicalUrl !== page.headerCanonicalUrl
- ) {
- report("canonical-conflict", {
- htmlCanonical: page.canonicalUrl,
- headerCanonical: page.headerCanonicalUrl,
- });
- }
- const effectiveCanonical = page.canonicalUrl ?? page.headerCanonicalUrl;
- if (effectiveCanonical && effectiveCanonical !== page.url) {
- report("canonicalized-page", { canonicalUrl: effectiveCanonical });
- }
-
// Content quality
if (page.isIndexable && page.wordCount < THIN_CONTENT_WORDS) {
report("thin-content", { wordCount: page.wordCount });
@@ -150,9 +161,6 @@ export function runPageReporters(page: CrawledPageResult): DetectedIssue[] {
if (page.isIndexable && page.links.length === 0) {
report("no-outgoing-links");
}
- if (page.crawlDepth !== null && page.crawlDepth >= DEEP_PAGE_DEPTH) {
- report("deep-page", { crawlDepth: page.crawlDepth });
- }
return issues;
}
diff --git a/src/server/lib/audit/lighthouse.test.ts b/src/server/lib/audit/lighthouse.test.ts
index 2c21a03b..5ce1f41a 100644
--- a/src/server/lib/audit/lighthouse.test.ts
+++ b/src/server/lib/audit/lighthouse.test.ts
@@ -12,14 +12,32 @@ vi.mock("@/server/lib/r2", () => ({
import { fetchLighthouseResult, selectLighthouseSample } from "./lighthouse";
+const okPage = (url: string) => ({
+ url,
+ statusCode: 200,
+ fetchClass: "ok" as const,
+});
+
describe("selectLighthouseSample", () => {
+ it("does not spend checks on a bot challenge that answered 200", () => {
+ const selected = selectLighthouseSample(
+ [
+ { ...okPage("https://example.com/"), fetchClass: "blocked" },
+ okPage("https://example.com/about"),
+ ],
+ "https://example.com/",
+ "auto",
+ );
+
+ expect(selected).toEqual(["https://example.com/about"]);
+ });
+
it("includes a start page reached through a trailing-slash redirect", () => {
const pages = [
- ...Array.from({ length: 10 }, (_, index) => ({
- url: `https://example.com/section${index}`,
- statusCode: 200,
- })),
- { url: "https://example.com/services/", statusCode: 200 },
+ ...Array.from({ length: 10 }, (_, index) =>
+ okPage(`https://example.com/section${index}`),
+ ),
+ okPage("https://example.com/services/"),
];
const selected = selectLighthouseSample(
@@ -35,8 +53,8 @@ describe("selectLighthouseSample", () => {
it("prefers an exact start page when both slash forms return 2xx", () => {
const selected = selectLighthouseSample(
[
- { url: "https://example.com/services/", statusCode: 200 },
- { url: "https://example.com/services", statusCode: 200 },
+ okPage("https://example.com/services/"),
+ okPage("https://example.com/services"),
],
"https://example.com/services",
"auto",
@@ -48,9 +66,9 @@ describe("selectLighthouseSample", () => {
it("does not sample another page from the start page's template", () => {
const selected = selectLighthouseSample(
[
- { url: "https://example.com/products/123", statusCode: 200 },
- { url: "https://example.com/products/456", statusCode: 200 },
- { url: "https://example.com/about", statusCode: 200 },
+ okPage("https://example.com/products/123"),
+ okPage("https://example.com/products/456"),
+ okPage("https://example.com/about"),
],
"https://example.com/products/123",
"auto",
diff --git a/src/server/lib/audit/lighthouse.ts b/src/server/lib/audit/lighthouse.ts
index 49ae29bf..38006033 100644
--- a/src/server/lib/audit/lighthouse.ts
+++ b/src/server/lib/audit/lighthouse.ts
@@ -2,11 +2,13 @@ import { detectUrlTemplate, canonicalUrlKey } from "./url-utils";
import type { BillingCustomerContext } from "@/server/billing/subscription";
import { createDataforseoClient } from "@/server/lib/dataforseo";
import type { LighthouseResult, LighthouseStrategy } from "./types";
+import type { PageFetchClass } from "@/shared/audit-fetch-class";
import { putTextToR2 } from "@/server/lib/r2";
interface LighthouseSamplePage {
url: string;
statusCode: number;
+ fetchClass: PageFetchClass;
}
function canonicalUrlKeyWithoutTrailingSlash(url: string): string {
@@ -119,9 +121,10 @@ export function selectLighthouseSample(
): string[] {
if (strategy === "none") return [];
- // Only consider pages that loaded successfully
+ // Only consider pages that loaded successfully. A bot challenge can answer
+ // 200, and a paid Lighthouse check of it measures the challenge.
const validPages = pages.filter(
- (p) => p.statusCode >= 200 && p.statusCode < 300,
+ (p) => p.statusCode >= 200 && p.statusCode < 300 && p.fetchClass === "ok",
);
// strategy === "auto": homepage + 1 per URL pattern, capped at 10
diff --git a/src/server/lib/audit/page-analyzer.test.ts b/src/server/lib/audit/page-analyzer.test.ts
index 557a5360..dec451c8 100644
--- a/src/server/lib/audit/page-analyzer.test.ts
+++ b/src/server/lib/audit/page-analyzer.test.ts
@@ -112,7 +112,8 @@ const PAGE_URL = "https://example.com/blog/post";
function expectParity(html: string) {
const streamed = analyzeHtml(html, PAGE_URL, 200, 0);
const reference = analyzeHtmlWithCheerio(html, PAGE_URL);
- expect(streamed).toEqual(reference);
+ const { javascriptShell: _javascriptShell, ...existingAnalysis } = streamed;
+ expect(existingAnalysis).toEqual(reference);
}
describe("analyzeHtml parity with the DOM reference", () => {
@@ -227,3 +228,43 @@ describe("analyzeHtml extraction caps", () => {
expect(analysis.images).toHaveLength(1_000);
});
});
+
+describe("JavaScript app-shell detection", () => {
+ it.each(["root", "app", "__next", "__nuxt"])(
+ "recognizes an empty %s app shell",
+ (id) => {
+ expect(
+ analyzeHtml(
+ `<body><div id="${id}">Loading...</div><script src="/app.js"></script></body>`,
+ PAGE_URL,
+ 200,
+ 0,
+ ).javascriptShell,
+ ).toBe(true);
+ },
+ );
+ it("recognizes Angular's app element", () => {
+ expect(
+ analyzeHtml(
+ '<app-root></app-root><script type="module" src="/main.js"></script>',
+ PAGE_URL,
+ 200,
+ 0,
+ ).javascriptShell,
+ ).toBe(true);
+ });
+ it.each([
+ '<div id="root"><h2>A server-rendered heading</h2></div><script src="/app.js"></script>',
+ '<div id="root"><a href="/about">About</a></div><script src="/app.js"></script>',
+ '<div id="app"><img src="/photo.png"></div><script src="/app.js"></script>',
+ '<div id="root"></div><script type="application/ld+json">{}</script>',
+ '<p>Short but valid content</p><script src="/analytics.js"></script>',
+ '<div id="root"></div>',
+ `<div id="root">${"Readable server-rendered content ".repeat(10)}</div><script src="/app.js"></script>`,
+ ])(
+ "does not confuse ordinary HTML, hydrated content, or structured data with a shell",
+ (html) => {
+ expect(analyzeHtml(html, PAGE_URL, 200, 0).javascriptShell).toBe(false);
+ },
+ );
+});
diff --git a/src/server/lib/audit/page-analyzer.ts b/src/server/lib/audit/page-analyzer.ts
index 47db8ce5..7dad80c0 100644
--- a/src/server/lib/audit/page-analyzer.ts
+++ b/src/server/lib/audit/page-analyzer.ts
@@ -35,6 +35,8 @@ const MAX_ANCHOR_CHARS = 200;
*/
const MAX_EXTRACTED_LINKS = 1_000;
const MAX_EXTRACTED_IMAGES = 1_000;
+// Common app entry points. Scripts alone also appear on ordinary HTML pages.
+const APP_ROOT_IDS = new Set(["root", "app", "__next", "__nuxt"]);
interface OpenAnchor {
href: string;
@@ -65,6 +67,8 @@ export function analyzeHtml(
let ogDescription: string | null = null;
let ogImage: string | null = null;
let hasStructuredData = false;
+ let hasAppRoot = false;
+ let hasExecutableScript = false;
const hreflangTags: string[] = [];
const h1s: string[] = [];
@@ -136,6 +140,9 @@ export function analyzeHtml(
}
if (name === "noscript") noscriptDepth += 1;
if (noscriptDepth > 0) return;
+ if (headDepth === 0 && suppressDepth === 0) {
+ hasAppRoot ||= APP_ROOT_IDS.has(attribs["id"]) || name === "app-root";
+ }
switch (name) {
case "title":
// Ignore <title> inside <svg> — only the document title counts.
@@ -166,6 +173,12 @@ export function analyzeHtml(
}
break;
case "script":
+ hasExecutableScript ||= [
+ "",
+ "module",
+ "text/javascript",
+ "application/javascript",
+ ].includes(attribs["type"]?.toLowerCase() ?? "");
if (attribs["type"] === "application/ld+json") {
hasStructuredData = true;
}
@@ -253,6 +266,13 @@ export function analyzeHtml(
headingOrder,
wordCount,
bodyText,
+ javascriptShell:
+ hasAppRoot &&
+ hasExecutableScript &&
+ wordCount < 20 &&
+ headingOrder.length === 0 &&
+ linksByTarget.size === 0 &&
+ images.length === 0,
images,
links: Array.from(linksByTarget.values()),
hasStructuredData,
diff --git a/src/server/lib/audit/rendered-page.test.ts b/src/server/lib/audit/rendered-page.test.ts
new file mode 100644
index 00000000..8946bf21
--- /dev/null
+++ b/src/server/lib/audit/rendered-page.test.ts
@@ -0,0 +1,242 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { RenderedPageService } from "./rendered-page";
+import { MAX_HTML_BYTES } from "./html-response";
+import { isAuditRenderingAllowed } from "./rendering-policy";
+
+const url = "https://example.com/page";
+const html =
+ "<html><head><title>Rendered</title></head><body>Loaded content</body></html>";
+const browser = { quickAction: vi.fn() };
+function cloudflare(
+ status = 200,
+ content = html,
+ finalUrl = url,
+ headers: Record<string, string> = {},
+) {
+ return Response.json({
+ success: true,
+ result: content,
+ meta: { status, finalUrl, headers },
+ });
+}
+function context(overrides: Record<string, unknown> = {}, status = 200) {
+ return Response.json(
+ {
+ success: true,
+ type: "html",
+ html,
+ metadata: { finalUrl: url },
+ finalDOMState: "loaded",
+ key_metadata: { credits_consumed: 1 },
+ ...overrides,
+ },
+ { status },
+ );
+}
+function render(
+ options: { browser?: typeof browser; contextApiKey?: string } = {
+ browser,
+ contextApiKey: "context-test-key",
+ },
+ target = url,
+) {
+ const usage = { cloudflareAttempts: 0, contextCredits: 0 };
+ const page = RenderedPageService.renderPage(target, {
+ ...options,
+ auditId: "audit",
+ usage,
+ });
+ return { page, usage };
+}
+
+beforeEach(() => {
+ vi.spyOn(console, "info").mockImplementation(() => {});
+});
+
+describe("rendered page providers", () => {
+ it("renders on Cloudflare with its full timeout and never calls Context", async () => {
+ browser.quickAction.mockResolvedValue(
+ cloudflare(200, html, url, { "set-cookie": "one\ntwo" }),
+ );
+ const fetchMock = vi.spyOn(globalThis, "fetch");
+ const { page, usage } = render();
+ expect(await page).toEqual({ html, status: 200 });
+ expect(usage).toEqual({ cloudflareAttempts: 1, contextCredits: 0 });
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(browser.quickAction).toHaveBeenCalledWith("content", {
+ url,
+ cacheTTL: 0,
+ gotoOptions: { waitUntil: "networkidle2", timeout: 20_000 },
+ });
+ });
+
+ it.each([
+ ["a bot challenge", cloudflare(200, "<title>Just a moment...</title>")],
+ [
+ "a mitigation header",
+ cloudflare(200, html, url, { "Cf-MiTiGaTeD": "challenge" }),
+ ],
+ ["an origin block", cloudflare(403)],
+ ["an origin error", cloudflare(503)],
+ ["a browser error", new Response(null, { status: 429 })],
+ ])(
+ "falls back to fresh full HTML from Context after %s, counting both attempts",
+ async (_case, cloudflareResponse) => {
+ browser.quickAction.mockResolvedValue(cloudflareResponse);
+ const fetchMock = vi
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue(context());
+ const { page, usage } = render();
+ expect(await page).toEqual({ html, status: null });
+ expect(usage).toEqual({ cloudflareAttempts: 1, contextCredits: 1 });
+ const [endpoint, request] = fetchMock.mock.calls[0];
+ if (!(endpoint instanceof URL)) throw new Error("Expected a URL request");
+ expect(endpoint.origin + endpoint.pathname).toBe(
+ "https://api.context.dev/v1/web/scrape/html",
+ );
+ expect(Object.fromEntries(endpoint.searchParams)).toMatchObject({
+ url,
+ maxAgeMs: "0",
+ useMainContentOnly: "false",
+ "timeoutOpts[behavior]": "fail",
+ "pdf[shouldParse]": "false",
+ });
+ expect(request?.headers).toEqual({
+ Authorization: "Bearer context-test-key",
+ });
+ },
+ );
+
+ it("does not mistake a background challenge script for a blocked page", async () => {
+ browser.quickAction.mockResolvedValue(
+ cloudflare(
+ 200,
+ '<html><head><title>Our products</title><script src="/challenge-platform/check"></script></head><body>Real content</body></html>',
+ ),
+ );
+ const fetchMock = vi.spyOn(globalThis, "fetch");
+ await render().page;
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("keeps the first 1 MiB of an oversized render, as the direct crawl does", async () => {
+ const head = "<html><head><title>Big page</title></head><body>";
+ browser.quickAction.mockResolvedValue(
+ cloudflare(200, head + "x".repeat(MAX_HTML_BYTES)),
+ );
+ const fetchMock = vi.spyOn(globalThis, "fetch");
+ const { html: rendered } = await render().page;
+ expect(rendered.startsWith(head)).toBe(true);
+ expect(new TextEncoder().encode(rendered).length).toBe(MAX_HTML_BYTES);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ cloudflare(200, html, "https://elsewhere.example/"),
+ cloudflare(200, " "),
+ Response.json({ success: true, result: html }),
+ ])(
+ "fails without a fallback when Cloudflare returns an unusable document",
+ async (response) => {
+ browser.quickAction.mockResolvedValue(response);
+ const { page, usage } = render({ browser });
+ await expect(page).rejects.toThrow("Unable to render");
+ expect(usage).toEqual({ cloudflareAttempts: 1, contextCredits: 0 });
+ },
+ );
+
+ it("renders through Context alone where there is no browser", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(context());
+ const { page, usage } = render({ contextApiKey: "context-test-key" });
+ expect(await page).toEqual({ html, status: null });
+ expect(usage).toEqual({ cloudflareAttempts: 0, contextCredits: 1 });
+ });
+
+ it.each([
+ { success: false },
+ { type: "pdf" },
+ { finalDOMState: "still-loading" },
+ { metadata: { finalUrl: "https://elsewhere.example/" } },
+ ])(
+ "rejects an unusable Context document %o but still counts its reported credit",
+ async (overrides) => {
+ browser.quickAction.mockRejectedValue(new Error("Browser failed"));
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(context(overrides));
+ const { page, usage } = render();
+ await expect(page).rejects.toThrow("Unable to render");
+ expect(usage.contextCredits).toBe(1);
+ },
+ );
+
+ it("counts usage reported on a Context HTTP error response", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ Response.json(
+ { error: "timeout", key_metadata: { credits_consumed: 1 } },
+ { status: 408 },
+ ),
+ );
+ const { page, usage } = render({ contextApiKey: "context-test-key" });
+ await expect(page).rejects.toThrow("Unable to render");
+ expect(usage.contextCredits).toBe(1);
+ });
+
+ it("fails once per provider without retrying, logging no provider payload", async () => {
+ browser.quickAction.mockRejectedValue(
+ new Error("private provider payload"),
+ );
+ const fetchMock = vi
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue(
+ new Response("private provider payload", { status: 429 }),
+ );
+ const { page, usage } = render();
+ await expect(page).rejects.toThrow("Unable to render");
+ // A failure that reports no usage is not charged as a Context credit.
+ expect(usage).toEqual({ cloudflareAttempts: 1, contextCredits: 0 });
+ expect(browser.quickAction).toHaveBeenCalledTimes(1);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(JSON.stringify(vi.mocked(console.info).mock.calls)).not.toContain(
+ "private provider payload",
+ );
+ });
+
+ it("assumes one credit for a usable Context page that omits its usage", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ context({ key_metadata: undefined }),
+ );
+ const { page, usage } = render({ contextApiKey: "context-test-key" });
+ await page;
+ expect(usage.contextCredits).toBe(1);
+ });
+
+ it.each([
+ "http://127.0.0.1/",
+ "http://metadata.google.internal/",
+ "https://name:[email protected]/",
+ "file:///etc/passwd",
+ ])("rejects unsafe target %s before calling a provider", async (target) => {
+ const fetchMock = vi.spyOn(globalThis, "fetch");
+ await expect(render(undefined, target).page).rejects.toThrow(
+ "Invalid rendering target",
+ );
+ expect(browser.quickAction).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe("rendering availability", () => {
+ afterEach(() => vi.unstubAllEnvs());
+
+ it("exists when a browser is bound or a Context key is set, whatever the auth mode", async () => {
+ // A legacy Wrangler install runs cloudflare_access with no browser.
+ vi.stubEnv("AUTH_MODE", "cloudflare_access");
+ expect(await isAuditRenderingAllowed()).toBe(false);
+ vi.stubEnv("CONTEXT_API_KEY", "context-test-key");
+ expect(await isAuditRenderingAllowed()).toBe(true);
+ // An Alchemy preview runs local_noauth with a browser.
+ vi.stubEnv("CONTEXT_API_KEY", "");
+ vi.stubEnv("AUTH_MODE", "local_noauth");
+ vi.stubEnv("AUDIT_BROWSER_RENDERING", "true");
+ expect(await isAuditRenderingAllowed()).toBe(true);
+ });
+});
diff --git a/src/server/lib/audit/rendered-page.ts b/src/server/lib/audit/rendered-page.ts
new file mode 100644
index 00000000..9a026834
--- /dev/null
+++ b/src/server/lib/audit/rendered-page.ts
@@ -0,0 +1,203 @@
+import { z } from "zod";
+import type {
+ BrowserRun,
+ Response as BrowserResponse,
+} from "@cloudflare/workers-types";
+import {
+ CLOUDFLARE_RENDER_TIMEOUT_MS,
+ type RenderUsage,
+} from "@/shared/audit-rendering";
+import { classifyFetch } from "./classify-fetch";
+import { MAX_HTML_BYTES, readTextUpTo, truncateToBytes } from "./html-response";
+import { isCrawlableUrl } from "./url-policy";
+import { normalizeUrl } from "./url-utils";
+
+type RenderOptions = {
+ // Either renderer may be missing: Docker has no browser binding, and the
+ // Context key is optional on self-hosted Cloudflare deployments.
+ browser?: Pick<BrowserRun, "quickAction">;
+ contextApiKey?: string;
+ auditId: string;
+ // Counts every provider attempt, including rejected ones: both providers
+ // bill a request whether or not the HTML turned out to be usable.
+ usage: RenderUsage;
+};
+
+const cloudflareSchema = z.object({
+ success: z.literal(true),
+ result: z.string(),
+ meta: z.object({
+ status: z.number().int(),
+ finalUrl: z.string().url(),
+ headers: z.record(z.string(), z.string()).optional(),
+ }),
+});
+// Context includes key_metadata on every authenticated response, error or not.
+const usageSchema = z.object({
+ key_metadata: z
+ .object({ credits_consumed: z.number().nonnegative().optional() })
+ .optional(),
+});
+const contextSchema = z.object({
+ success: z.literal(true),
+ type: z.literal("html"),
+ html: z.string(),
+ metadata: z.object({ finalUrl: z.string().url() }),
+ finalDOMState: z.literal("loaded"),
+});
+
+// JSON escaping can expand an HTML byte up to sixfold. Bound the transport
+// before JSON.parse as well as the decoded HTML before it reaches the parser.
+// A body cut off at the bound is incomplete JSON, so parsing rejects it.
+const MAX_RESPONSE_BYTES = 8 * MAX_HTML_BYTES;
+async function readProviderJson(
+ response: Response | BrowserResponse,
+): Promise<unknown> {
+ return JSON.parse(await readTextUpTo(response, MAX_RESPONSE_BYTES));
+}
+
+/**
+ * The rendered HTML to analyze: the same first 1 MiB the direct crawl keeps,
+ * which still holds the metadata and navigation the audit reads.
+ */
+function usableHtml(url: string, finalUrl: string, html: string) {
+ // The existing direct fetch records redirects one hop at a time. A browser
+ // must not silently substitute another URL's content into this page row.
+ if (normalizeUrl(finalUrl, url) !== normalizeUrl(url, url)) {
+ throw new Error("Rendering returned a different URL");
+ }
+ if (!html.trim()) throw new Error("Rendered HTML is empty");
+ return truncateToBytes(html, MAX_HTML_BYTES);
+}
+
+/** The rendered HTML, with the origin's status when the renderer reports it. */
+export type RenderedPage = { html: string; status: number | null };
+
+/** Null when Cloudflare failed, was blocked, or saw an origin error. */
+async function renderWithCloudflare(
+ url: string,
+ browser: Pick<BrowserRun, "quickAction">,
+): Promise<RenderedPage | null> {
+ try {
+ const response = await browser.quickAction("content", {
+ url,
+ cacheTTL: 0,
+ gotoOptions: {
+ waitUntil: "networkidle2",
+ timeout: CLOUDFLARE_RENDER_TIMEOUT_MS,
+ },
+ });
+ if (!response.ok) {
+ await response.body?.cancel();
+ return null;
+ }
+ const data = cloudflareSchema.parse(await readProviderJson(response));
+ const { status, finalUrl, headers } = data.meta;
+ const html = usableHtml(url, finalUrl, data.result);
+ const mitigated = Object.entries(headers ?? {}).some(
+ ([name, value]) =>
+ name.toLowerCase() === "cf-mitigated" && Boolean(value.trim()),
+ );
+ if (
+ status >= 400 ||
+ classifyFetch(status, mitigated, html.slice(0, 4_000)) !== "ok"
+ ) {
+ return null;
+ }
+ return { html, status };
+ } catch {
+ // Provider bodies/errors can contain page data. Nothing raw is logged.
+ return null;
+ }
+}
+
+async function renderWithContext(
+ url: string,
+ contextApiKey: string,
+): Promise<{
+ html: string | null;
+ credits: number;
+ httpStatus: number | null;
+}> {
+ const endpoint = new URL("https://api.context.dev/v1/web/scrape/html");
+ endpoint.search = new URLSearchParams({
+ url,
+ maxAgeMs: "0",
+ useMainContentOnly: "false",
+ waitForMs: "1000",
+ "pdf[shouldParse]": "false",
+ "timeoutOpts[milliseconds]": "30000",
+ "timeoutOpts[behavior]": "fail",
+ }).toString();
+
+ let html: string | null = null;
+ let creditsUsed: number | null = null;
+ let httpStatus: number | null = null;
+ try {
+ const response = await fetch(endpoint, {
+ headers: { Authorization: `Bearer ${contextApiKey}` },
+ signal: AbortSignal.timeout(35_000),
+ });
+ httpStatus = response.status;
+ const json = await readProviderJson(response);
+ // Usage first: a rejected or partial document still cost a credit.
+ const usage = usageSchema.safeParse(json);
+ creditsUsed = usage.success
+ ? (usage.data.key_metadata?.credits_consumed ?? null)
+ : null;
+ if (!response.ok) throw new Error(`Rendering provider HTTP ${httpStatus}`);
+ const data = contextSchema.parse(json);
+ html = usableHtml(url, data.metadata.finalUrl, data.html);
+ } catch {
+ // Provider bodies/errors can contain page data or credentials. Nothing
+ // raw is logged, and a paid call is never retried automatically.
+ }
+ // Context charges one credit per scrape. Bill what it reports; only assume
+ // one credit for a usable page that omits its usage, never for a failure.
+ return { html, credits: creditsUsed ?? (html ? 1 : 0), httpStatus };
+}
+
+/**
+ * Cloudflare Browser Run first, because it costs a fraction of Context. Context
+ * renders only the pages Cloudflare could not: a failure, a bot challenge, or
+ * an origin error.
+ */
+async function renderPage(
+ url: string,
+ options: RenderOptions,
+): Promise<RenderedPage> {
+ if (!isCrawlableUrl(url) || new URL(url).username || new URL(url).password) {
+ throw new Error("Invalid rendering target");
+ }
+
+ if (options.browser) {
+ const page = await renderWithCloudflare(url, options.browser);
+ options.usage.cloudflareAttempts += 1;
+ console.info("site_audit:render", {
+ auditId: options.auditId,
+ provider: "cloudflare",
+ outcome: page ? "ok" : "fallback",
+ });
+ if (page) return page;
+ }
+
+ if (options.contextApiKey) {
+ const { html, credits, httpStatus } = await renderWithContext(
+ url,
+ options.contextApiKey,
+ );
+ options.usage.contextCredits += credits;
+ console.info("site_audit:render", {
+ auditId: options.auditId,
+ provider: "context",
+ httpStatus,
+ creditsUsed: credits,
+ outcome: html ? "ok" : "error",
+ });
+ // Context reports no origin status.
+ if (html) return { html, status: null };
+ }
+ throw new Error("Unable to render this page");
+}
+
+export const RenderedPageService = { renderPage } as const;
diff --git a/src/server/lib/audit/rendering-billing.test.ts b/src/server/lib/audit/rendering-billing.test.ts
new file mode 100644
index 00000000..4ff2ded6
--- /dev/null
+++ b/src/server/lib/audit/rendering-billing.test.ts
@@ -0,0 +1,165 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { finalizeHold, holdCredits } from "@/server/billing/subscription";
+
+const mocks = vi.hoisted(() => ({
+ isHosted: vi.fn(),
+ getUsageCreditsRemaining: vi.fn(),
+ holdCredits: vi.fn<typeof holdCredits>(),
+ finalizeHold: vi.fn<typeof finalizeHold>(),
+}));
+vi.mock("@/server/lib/runtime-env", () => ({
+ isHostedServerAuthMode: mocks.isHosted,
+}));
+vi.mock("@/server/billing/subscription", () => ({
+ getOrCreateOrganizationCustomer: vi.fn().mockResolvedValue({ id: "org" }),
+ getUsageCreditsRemaining: mocks.getUsageCreditsRemaining,
+ holdCredits: mocks.holdCredits,
+ finalizeHold: mocks.finalizeHold,
+}));
+vi.mock("@/server/lib/posthog", () => ({ captureServerEvent: vi.fn() }));
+
+import {
+ lockRenderingCredits,
+ settleRenderingLocks,
+} from "./rendering-billing";
+import { estimateRenderingCredits } from "@/shared/audit-rendering";
+
+const customer = {
+ userId: "user",
+ userEmail: "[email protected]",
+ organizationId: "org",
+};
+// 100 pages hold 384 credits: every page falling back to Context.
+const lockFor100Pages = () =>
+ lockRenderingCredits({ customer, auditId: "audit", maxPages: 100 });
+const monthlyLock = {
+ lockId: "monthly",
+ featureId: "usage_credits" as const,
+ estimatedCredits: 300,
+ callIndexes: [],
+};
+const topupLock = {
+ lockId: "topup",
+ featureId: "topup_credits" as const,
+ estimatedCredits: 84,
+ callIndexes: [],
+};
+
+beforeEach(() => {
+ mocks.isHosted.mockResolvedValue(true);
+ mocks.getUsageCreditsRemaining.mockResolvedValue({
+ monthlyRemaining: 300,
+ topupRemaining: 1_000,
+ });
+ mocks.holdCredits.mockImplementation(
+ async ({ featureId, estimatedCredits }) => ({
+ hold: { lockId: featureId, featureId, estimatedCredits, callIndexes: [] },
+ allowed: true,
+ balance: null,
+ }),
+ );
+ mocks.finalizeHold.mockResolvedValue({ landed: true });
+});
+
+describe("rendering estimate", () => {
+ it("ranges from every page on Cloudflare to every page on Context", () => {
+ expect(estimateRenderingCredits(100)).toEqual({ low: 64, high: 384 });
+ });
+});
+
+describe("rendering credit lock", () => {
+ it("leaves self-hosted rendering unmetered", async () => {
+ mocks.isHosted.mockResolvedValue(false);
+ expect(await lockFor100Pages()).toEqual([]);
+ expect(mocks.holdCredits).not.toHaveBeenCalled();
+ });
+
+ it("holds the worst case from the monthly balance first, then top-up, for at most 24 hours", async () => {
+ const locks = await lockFor100Pages();
+ expect(
+ locks.map((lock) => [lock.featureId, lock.estimatedCredits]),
+ ).toEqual([
+ ["usage_credits", 300],
+ ["topup_credits", 84],
+ ]);
+ const ttlMs = mocks.holdCredits.mock.calls[0][0].ttlMs ?? 0;
+ expect(ttlMs).toBeGreaterThan(60 * 60_000);
+ expect(ttlMs).toBeLessThanOrEqual(24 * 60 * 60_000);
+ });
+
+ it("refuses before holding anything when both balances together fall short", async () => {
+ mocks.getUsageCreditsRemaining.mockResolvedValue({
+ monthlyRemaining: 300,
+ topupRemaining: 83,
+ });
+ const error = await lockFor100Pages().catch((reason: unknown) => reason);
+ expect(error).toMatchObject({ code: "INSUFFICIENT_CREDITS" });
+ expect(String(error)).toContain("needs $0.39 of credits");
+ expect(mocks.holdCredits).not.toHaveBeenCalled();
+ });
+
+ it("releases the monthly hold when the top-up hold is refused", async () => {
+ mocks.holdCredits
+ .mockResolvedValueOnce({
+ hold: monthlyLock,
+ allowed: true,
+ balance: null,
+ })
+ .mockResolvedValueOnce({
+ hold: topupLock,
+ allowed: false,
+ balance: null,
+ });
+ await expect(lockFor100Pages()).rejects.toMatchObject({
+ code: "INSUFFICIENT_CREDITS",
+ });
+ expect(mocks.finalizeHold).toHaveBeenCalledTimes(1);
+ expect(mocks.finalizeHold).toHaveBeenCalledWith(
+ monthlyLock,
+ 0,
+ expect.anything(),
+ );
+ });
+});
+
+describe("rendering settlement", () => {
+ const locks = [monthlyLock, topupLock];
+
+ it("confirms the credits used from the monthly hold and releases the rest", async () => {
+ // 10 Cloudflare attempts and 2 Context credits cost $0.01: 13 credits.
+ await settleRenderingLocks({
+ customer,
+ auditId: "audit",
+ locks,
+ usage: { cloudflareAttempts: 10, contextCredits: 2 },
+ });
+ expect(
+ mocks.finalizeHold.mock.calls.map(([lock, credits]) => [
+ lock.lockId,
+ credits,
+ ]),
+ ).toEqual([
+ ["monthly", 13],
+ ["topup", 0],
+ ]);
+ });
+
+ it("never charges more than the hold, and survives a finalize that did not land", async () => {
+ mocks.finalizeHold.mockResolvedValueOnce({
+ landed: false,
+ error: new Error("Autumn down"),
+ });
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ await settleRenderingLocks({
+ customer,
+ auditId: "audit",
+ locks,
+ usage: { cloudflareAttempts: 200, contextCredits: 200 },
+ });
+ expect(mocks.finalizeHold).toHaveBeenLastCalledWith(
+ topupLock,
+ 84,
+ expect.anything(),
+ );
+ });
+});
diff --git a/src/server/lib/audit/rendering-billing.ts b/src/server/lib/audit/rendering-billing.ts
new file mode 100644
index 00000000..1ccb8cf4
--- /dev/null
+++ b/src/server/lib/audit/rendering-billing.ts
@@ -0,0 +1,162 @@
+import {
+ finalizeHold,
+ getOrCreateOrganizationCustomer,
+ getUsageCreditsRemaining,
+ holdCredits,
+ type BillingCustomerContext,
+ type UsageCreditHold,
+} from "@/server/billing/subscription";
+import { AppError } from "@/server/lib/errors";
+import { captureServerEvent } from "@/server/lib/posthog";
+import { isHostedServerAuthMode } from "@/server/lib/runtime-env";
+import {
+ estimateRenderingCredits,
+ renderingCreditsNeededText,
+ renderUsageCredits,
+ type RenderUsage,
+} from "@/shared/audit-rendering";
+import {
+ AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
+} from "@/shared/billing";
+
+// Autumn allows 24 hours at most; keep a minute of margin for clock skew. An
+// audit that dies without settling returns its hold when the lock expires.
+const LOCK_TTL_MS = 24 * 60 * 60_000 - 60_000;
+
+/** Credits held for one rendered audit, monthly balance first, then top-up. */
+export type RenderingLock = UsageCreditHold;
+
+/**
+ * Holds the worst-case rendering cost of a hosted audit before it starts:
+ * every page falling back to Context. Throws INSUFFICIENT_CREDITS when the
+ * monthly and top-up balances together cannot cover it. Returns no locks
+ * outside hosted mode, where rendering is unmetered.
+ *
+ * Unlike a single DataForSEO call, one audit's hold is large enough to split:
+ * the monthly balance covers what it can and top-up covers the rest.
+ */
+export async function lockRenderingCredits(input: {
+ customer: BillingCustomerContext;
+ auditId: string;
+ maxPages: number;
+}): Promise<RenderingLock[]> {
+ if (!(await isHostedServerAuthMode())) return [];
+ const { id: customerId } = await getOrCreateOrganizationCustomer(
+ input.customer,
+ );
+ const required = estimateRenderingCredits(input.maxPages).high;
+ const insufficient = new AppError(
+ "INSUFFICIENT_CREDITS",
+ renderingCreditsNeededText(input.maxPages),
+ );
+ const balances = await getUsageCreditsRemaining(customerId);
+ // Clamp at 0: a balance can read negative after an overdraft.
+ const monthly = Math.min(Math.max(balances.monthlyRemaining, 0), required);
+ const topup = required - monthly;
+ if (topup > Math.max(balances.topupRemaining, 0)) throw insufficient;
+
+ const properties = {
+ creditFeature: "site_audit",
+ source: "site_audit_rendering",
+ auditId: input.auditId,
+ };
+ const locks: RenderingLock[] = [];
+ try {
+ for (const [featureId, credits] of [
+ [AUTUMN_SEO_DATA_BALANCE_FEATURE_ID, monthly],
+ [AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID, topup],
+ ] as const) {
+ if (credits <= 0) continue;
+ const { hold, allowed } = await holdCredits({
+ customerId,
+ featureId,
+ estimatedCredits: credits,
+ // Covers the audit's renders, not any DataForSEO calls.
+ callIndexes: [],
+ properties,
+ ttlMs: LOCK_TTL_MS,
+ lockPrefix: "render",
+ });
+ // The balance moved between the read and the hold.
+ if (!allowed) throw insufficient;
+ locks.push(hold);
+ }
+ } catch (error) {
+ await releaseRenderingLocks(locks);
+ throw error;
+ }
+ return locks;
+}
+
+/** Returns every held credit, for an audit that never started. */
+export async function releaseRenderingLocks(locks: RenderingLock[]) {
+ for (const lock of locks) {
+ const { landed, error } = await finalizeHold(lock, 0, {
+ source: "site_audit_rendering",
+ });
+ // The lock still expires on its own.
+ if (!landed) {
+ console.error("site_audit:render_lock_release_failed", {
+ lockId: lock.lockId,
+ error,
+ });
+ }
+ }
+}
+
+/**
+ * Charges the credits the audit used against its locks, monthly first, and
+ * releases the rest. Never throws: a settlement that fails leaves the hold to
+ * expire, which returns it to the customer.
+ */
+export async function settleRenderingLocks(input: {
+ customer: BillingCustomerContext;
+ auditId: string;
+ locks: RenderingLock[];
+ usage: RenderUsage;
+}) {
+ let remaining = renderUsageCredits(input.usage);
+ const charged = { monthly: 0, topup: 0 };
+ for (const lock of input.locks) {
+ // A retried chunk can render a page twice; the hold is the most we charge.
+ const charge = Math.min(remaining, lock.estimatedCredits);
+ remaining -= charge;
+ const { landed, error } = await finalizeHold(lock, charge, {
+ source: "site_audit_rendering",
+ auditId: input.auditId,
+ ...input.usage,
+ });
+ if (!landed) {
+ console.error("site_audit:render_settle_failed", {
+ auditId: input.auditId,
+ lockId: lock.lockId,
+ charge,
+ error,
+ });
+ continue;
+ }
+ if (lock.featureId === AUTUMN_SEO_DATA_BALANCE_FEATURE_ID) {
+ charged.monthly += charge;
+ } else {
+ charged.topup += charge;
+ }
+ }
+ const total = charged.monthly + charged.topup;
+ if (total <= 0) return;
+ await captureServerEvent({
+ distinctId: input.customer.userId,
+ event: "usage:credits_consume",
+ organizationId: input.customer.organizationId,
+ properties: {
+ project_id: input.customer.projectId,
+ credit_feature: "site_audit",
+ source: "site_audit_rendering",
+ monthly_credits: charged.monthly,
+ topup_credits: charged.topup,
+ total_credits: total,
+ cloudflare_attempts: input.usage.cloudflareAttempts,
+ context_credits: input.usage.contextCredits,
+ },
+ });
+}
diff --git a/src/server/lib/audit/rendering-policy.ts b/src/server/lib/audit/rendering-policy.ts
new file mode 100644
index 00000000..2032a34a
--- /dev/null
+++ b/src/server/lib/audit/rendering-policy.ts
@@ -0,0 +1,13 @@
+import { getOptionalEnvValue } from "@/server/lib/runtime-env";
+
+// Rendering works when a renderer exists. Alchemy deployments (hosted,
+// previews, self-hosted Cloudflare) bind Browser Run to the audit worker and
+// set AUDIT_BROWSER_RENDERING on the app worker; local development sets the
+// same flag to attach a remote browser. Docker and legacy Wrangler installs
+// have no browser, so they render only through a Context.dev key.
+// Hosted accounts pay for rendering with usage credits; self-hosted operators
+// pay their own Cloudflare and Context accounts.
+export async function isAuditRenderingAllowed(): Promise<boolean> {
+ if (await getOptionalEnvValue("CONTEXT_API_KEY")) return true;
+ return (await getOptionalEnvValue("AUDIT_BROWSER_RENDERING")) === "true";
+}
diff --git a/src/server/lib/audit/types.ts b/src/server/lib/audit/types.ts
index 37c9ceef..4b623412 100644
--- a/src/server/lib/audit/types.ts
+++ b/src/server/lib/audit/types.ts
@@ -12,6 +12,7 @@ export type LighthouseStrategy = "auto" | "none";
export interface AuditConfig {
maxPages: number;
lighthouseStrategy: LighthouseStrategy;
+ renderJavaScript?: boolean;
/** Detected from the start URL's `powered-by` response header. */
sitePlatform?: "shopify";
/** Which crawler-access credential the crawl replayed, if any. */
@@ -34,6 +35,7 @@ const lighthouseStrategySchema = z
const auditConfigSchema = z.object({
maxPages: z.number().int().min(MIN_AUDIT_PAGES).max(PAID_MAX_AUDIT_PAGES),
lighthouseStrategy: lighthouseStrategySchema,
+ renderJavaScript: z.boolean().optional().default(false),
// Absent on every audit stored before crawler access shipped, and a future
// platform value must not make an old report unviewable.
sitePlatform: z.literal("shopify").optional().catch(undefined),
@@ -79,6 +81,8 @@ export interface PageAnalysis {
// Content
wordCount: number;
bodyText: string;
+ /** Conservative signal of an app shell, not proof of missing content. */
+ javascriptShell?: boolean;
// Images
images: Array<{ src: string | null; alt: string | null }>;
@@ -146,6 +150,8 @@ export interface CrawledPageResult {
* checked; a PDF must not). Transient — not persisted.
*/
isHtml: boolean;
+ /** App shell, rendered or not; transient signal for the per-page issue reporter. */
+ javascriptShell?: boolean;
/**
* HTML size read for this page (approximate; capped at MAX_HTML_BYTES).
* Transient — feeds the crawl window's memory-pressure signal, since
diff --git a/src/server/lib/setup-status.ts b/src/server/lib/setup-status.ts
index 8e0c0210..71932d62 100644
--- a/src/server/lib/setup-status.ts
+++ b/src/server/lib/setup-status.ts
@@ -29,6 +29,7 @@ const CHECK_ENV_VARS = [
"GOOGLE_CLIENT_SECRET",
"BETTER_AUTH_SECRET",
"OPENROUTER_API_KEY",
+ "CONTEXT_API_KEY",
] as const;
const LEVEL_TO_STATUS = {
diff --git a/src/server/mcp/tools/site-audit-tools.ts b/src/server/mcp/tools/site-audit-tools.ts
index dabb7e3a..e2dfe2b5 100644
--- a/src/server/mcp/tools/site-audit-tools.ts
+++ b/src/server/mcp/tools/site-audit-tools.ts
@@ -18,6 +18,8 @@ import {
} from "@/server/mcp/output-schemas";
import { withMcpProjectAuth } from "@/server/mcp/project-auth";
import { projectIdSchema } from "@/server/mcp/schemas";
+import { renderingEstimateText } from "@/shared/audit-rendering";
+import { RENDERED_MAX_AUDIT_PAGES } from "@/shared/audit-limits";
const auditIdSchema = z
.string()
@@ -55,6 +57,12 @@ const runInputSchema = {
.max(10_000)
.optional()
.describe("Page budget for the crawl (default 50)."),
+ renderJavaScript: z
+ .boolean()
+ .optional()
+ .describe(
+ `Render JavaScript before auditing, for sites whose content or links load client-side or whose bot protection blocks the plain crawler. Slower, and limited to ${RENDERED_MAX_AUDIT_PAGES.toLocaleString("en-US")} pages. On hosted plans: ${renderingEstimateText(100)} Billing counts pages actually rendered. Hosted plans hold the high end until the audit ends; an account that cannot cover it is refused. Default false.`,
+ ),
runLighthouse: z
.boolean()
.optional()
@@ -102,6 +110,7 @@ export const runSiteAuditTool = {
maxPages: args.maxPages,
lighthouseStrategy,
limitTier,
+ renderJavaScript: args.renderJavaScript,
}));
} catch (error) {
// Expected refusals become readable answers instead of protocol errors:
@@ -111,7 +120,13 @@ export const runSiteAuditTool = {
? "Audit capacity reached for this account — delete old audits in the dashboard to free capacity, then try again."
: error instanceof AppError && error.code === "AUDIT_ALREADY_RUNNING"
? "This account is at its limit of concurrently running audits. Poll get_audit_status until one finishes, then try again."
- : null;
+ : // startAudit refuses only rendering with FORBIDDEN; its message
+ // says why and what to do instead.
+ error instanceof AppError &&
+ error.code === "FORBIDDEN" &&
+ args.renderJavaScript
+ ? error.message
+ : null;
if (refusalText) {
return mcpResponse({
text: refusalText,
diff --git a/src/server/workflows/SiteAuditWorkflow.test.ts b/src/server/workflows/SiteAuditWorkflow.test.ts
new file mode 100644
index 00000000..ba3397dc
--- /dev/null
+++ b/src/server/workflows/SiteAuditWorkflow.test.ts
@@ -0,0 +1,122 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { WorkflowStep } from "cloudflare:workers";
+import type { runAuditPhases } from "./siteAuditWorkflowPhases";
+
+const mocks = vi.hoisted(() => ({
+ runAuditPhases: vi.fn<typeof runAuditPhases>(),
+ settle: vi.fn(),
+ failAudit: vi.fn(),
+}));
+
+vi.mock("cloudflare:workers", () => ({ WorkflowEntrypoint: vi.fn() }));
+vi.mock("@/db", () => ({ withPgClient: (fn: () => unknown) => fn() }));
+vi.mock("@/server/workflows/pgStep", () => ({
+ pgStep: (
+ _step: unknown,
+ _name: string,
+ _config: unknown,
+ fn: () => unknown,
+ ) => fn(),
+}));
+vi.mock("@/server/workflows/siteAuditWorkflowPhases", () => ({
+ runAuditPhases: mocks.runAuditPhases,
+}));
+vi.mock("@/server/lib/audit/rendering-billing", () => ({
+ settleRenderingLocks: mocks.settle,
+}));
+vi.mock("@/server/features/audit/repositories/AuditRepository", () => ({
+ AuditRepository: {
+ getAuditForWorkflow: vi
+ .fn()
+ .mockResolvedValue({ projectId: "project", currentPhase: "crawling" }),
+ failAudit: mocks.failAudit,
+ },
+}));
+vi.mock("@/server/features/audit/services/CrawlerCredentialService", () => ({
+ CrawlerCredentialService: { openCrawlerAccess: vi.fn() },
+}));
+vi.mock("@/server/lib/posthog", () => ({
+ captureServerError: vi.fn(),
+ captureServerEvent: vi.fn(),
+}));
+
+import { SiteAuditWorkflow } from "./SiteAuditWorkflow";
+
+const locks = [
+ {
+ lockId: "lock",
+ featureId: "usage_credits" as const,
+ estimatedCredits: 384,
+ callIndexes: [],
+ },
+];
+const step = {
+ do: (_name: string, _config: unknown, fn: () => unknown) => fn(),
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- only step.do is reached; pgStep is mocked
+} as unknown as WorkflowStep;
+
+function run() {
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the mocked base class does not inspect Worker constructor context
+ const workflow = new SiteAuditWorkflow({} as ExecutionContext, {} as Env);
+ return workflow.run(
+ {
+ instanceId: "audit",
+ timestamp: new Date(),
+ payload: {
+ auditId: "audit",
+ billingCustomer: {
+ userId: "user",
+ userEmail: "[email protected]",
+ organizationId: "org",
+ },
+ projectId: "project",
+ startUrl: "https://example.com/",
+ config: { maxPages: 100, lighthouseStrategy: "none" },
+ renderLocks: locks,
+ },
+ },
+ step,
+ );
+}
+
+describe("rendered audit settlement", () => {
+ beforeEach(() => {
+ mocks.runAuditPhases.mockImplementation(async (_step, params) => {
+ params.renderUsage.cloudflareAttempts += 3;
+ params.renderUsage.contextCredits += 1;
+ });
+ });
+
+ it("settles the lock once with what the audit rendered", async () => {
+ await run();
+ expect(mocks.settle).toHaveBeenCalledTimes(1);
+ expect(mocks.settle).toHaveBeenCalledWith(
+ expect.objectContaining({
+ locks,
+ usage: { cloudflareAttempts: 3, contextCredits: 1 },
+ }),
+ );
+ });
+
+ it("settles what a failed audit rendered before it failed", async () => {
+ mocks.runAuditPhases.mockImplementation(async (_step, params) => {
+ params.renderUsage.cloudflareAttempts += 3;
+ throw new Error("crawl failed");
+ });
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ await expect(run()).rejects.toThrow("crawl failed");
+ expect(mocks.settle).toHaveBeenCalledTimes(1);
+ expect(mocks.settle).toHaveBeenCalledWith(
+ expect.objectContaining({
+ usage: { cloudflareAttempts: 3, contextCredits: 0 },
+ }),
+ );
+ });
+
+ it("does not mark a completed audit failed when settlement fails", async () => {
+ mocks.settle.mockRejectedValue(new Error("settle step timed out"));
+ await expect(run()).rejects.toThrow("settle step timed out");
+ expect(mocks.settle).toHaveBeenCalledTimes(1);
+ expect(mocks.failAudit).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/workflows/SiteAuditWorkflow.ts b/src/server/workflows/SiteAuditWorkflow.ts
index 7e94b04b..d26d8c63 100644
--- a/src/server/workflows/SiteAuditWorkflow.ts
+++ b/src/server/workflows/SiteAuditWorkflow.ts
@@ -17,11 +17,19 @@ import {
type SealedCrawlerAccess,
} from "@/server/features/audit/services/CrawlerCredentialService";
import { classifyAuditError } from "@/server/lib/audit/audit-errors";
+import {
+ settleRenderingLocks,
+ type RenderingLock,
+} from "@/server/lib/audit/rendering-billing";
import type { AuditConfig } from "@/server/lib/audit/types";
import { captureServerError, captureServerEvent } from "@/server/lib/posthog";
import { runAuditPhases } from "@/server/workflows/siteAuditWorkflowPhases";
import { pgStep } from "@/server/workflows/pgStep";
-import { DB_STEP } from "@/server/workflows/auditStepConfigs";
+import {
+ DB_STEP,
+ SETTLE_RENDERING_STEP,
+} from "@/server/workflows/auditStepConfigs";
+import type { RenderUsage } from "@/shared/audit-rendering";
interface AuditParams {
auditId: string;
@@ -37,6 +45,8 @@ interface AuditParams {
* below, outside any step whose result would be checkpointed.
*/
access?: SealedCrawlerAccess | null;
+ /** Credits held for a hosted rendered audit, settled when the audit ends. */
+ renderLocks?: RenderingLock[];
}
export class SiteAuditWorkflow extends WorkflowEntrypoint<Env, AuditParams> {
@@ -53,6 +63,11 @@ export class SiteAuditWorkflow extends WorkflowEntrypoint<Env, AuditParams> {
) {
const { auditId, billingCustomer, projectId, startUrl, config, access } =
event.payload;
+ // Summed from checkpointed chunk results, so a replay rebuilds it exactly.
+ const renderUsage: RenderUsage = {
+ cloudflareAttempts: 0,
+ contextCredits: 0,
+ };
try {
// Inside a step so the D1 read is retried and replay-cached; a bare
@@ -81,6 +96,7 @@ export class SiteAuditWorkflow extends WorkflowEntrypoint<Env, AuditParams> {
startUrl,
config,
access: await CrawlerCredentialService.openCrawlerAccess(access),
+ renderUsage,
});
} catch (error) {
console.error(`Audit ${auditId} failed:`, error);
@@ -133,6 +149,21 @@ export class SiteAuditWorkflow extends WorkflowEntrypoint<Env, AuditParams> {
});
});
throw error;
+ } finally {
+ // Once, whether the audit completed or failed, after the failure is
+ // recorded. Outside the try so a settlement error cannot fail a
+ // completed audit.
+ const locks = event.payload.renderLocks ?? [];
+ if (locks.length > 0) {
+ await pgStep(step, "settle-render-credits", SETTLE_RENDERING_STEP, () =>
+ settleRenderingLocks({
+ customer: billingCustomer,
+ auditId,
+ locks,
+ usage: renderUsage,
+ }),
+ );
+ }
}
}
}
diff --git a/src/server/workflows/auditStepConfigs.ts b/src/server/workflows/auditStepConfigs.ts
index 8632b636..cb1f83b0 100644
--- a/src/server/workflows/auditStepConfigs.ts
+++ b/src/server/workflows/auditStepConfigs.ts
@@ -30,6 +30,15 @@ export const LIGHTHOUSE_FETCH_STEP: WorkflowStepConfig = {
timeout: "5 minutes",
};
+/**
+ * Confirms a rendered audit's credit lock. Finalizing a lock twice is refused,
+ * so a replay must not run it again; a failed settlement expires on its own.
+ */
+export const SETTLE_RENDERING_STEP: WorkflowStepConfig = {
+ retries: { limit: 0, delay: "1 second" },
+ timeout: "1 minute",
+};
+
/** R2 + DB persistence is idempotent and safe to retry after the paid step. */
export const LIGHTHOUSE_PERSIST_STEP: WorkflowStepConfig = {
retries: { limit: 3, delay: "5 seconds", backoff: "exponential" },
diff --git a/src/server/workflows/site-audit-workflow-helpers.ts b/src/server/workflows/site-audit-workflow-helpers.ts
index 6d16c12f..a09e49ba 100644
--- a/src/server/workflows/site-audit-workflow-helpers.ts
+++ b/src/server/workflows/site-audit-workflow-helpers.ts
@@ -1,4 +1,7 @@
+import { MAX_HTML_BYTES, readTextUpTo } from "@/server/lib/audit/html-response";
+import { classifyFetch } from "@/server/lib/audit/classify-fetch";
import type { CrawledPageResult } from "@/server/lib/audit/types";
+import type { RenderedPage } from "@/server/lib/audit/rendered-page";
import type { PageFetchClass } from "@/shared/audit-fetch-class";
import { sha256Hex } from "@/server/lib/audit/ids";
import { normalizeUrl } from "@/server/lib/audit/url-utils";
@@ -6,40 +9,6 @@ import type { CrawlThrottle } from "@/server/lib/audit/crawl-throttle";
import { crawlerHeadersFor, type CrawlerAccess } from "@/shared/crawler-access";
const CRAWL_USER_AGENT = "OpenSEO-Audit/1.0";
-const MAX_HTML_BYTES = 1024 * 1024;
-
-/**
- * Markers of a bot-mitigation challenge page. We classify these honestly as
- * "blocked" instead of recording the challenge HTML as if it were the page.
- */
-const CHALLENGE_BODY_MARKERS = [
- "just a moment...",
- "challenge-platform",
- "cf-browser-verification",
- "attention required! | cloudflare",
- "verifying you are human",
-];
-
-function classifyFetch(
- statusCode: number,
- headers: Headers,
- bodySnippet: string,
-): PageFetchClass {
- if (statusCode === 0) return "error";
- // A final 429 means rate limiting, whether retries were exhausted or the
- // requested cooldown exceeded the crawl budget. Checked before
- // cf-mitigated: a Cloudflare rate-limiting rule sets that header too.
- if (statusCode === 429) return "rate_limited";
- if (headers.get("cf-mitigated")) return "blocked";
- if (statusCode === 401 || statusCode === 403) return "blocked";
- if (statusCode === 503) {
- const snippet = bodySnippet.toLowerCase();
- if (CHALLENGE_BODY_MARKERS.some((marker) => snippet.includes(marker))) {
- return "blocked";
- }
- }
- return "ok";
-}
/** Parse `Link: <url>; rel="canonical"` response headers. */
function parseLinkHeaderCanonical(
@@ -113,15 +82,20 @@ export async function crawlPage(
crawlDepth: number | null,
inSitemap: boolean,
throttle: CrawlThrottle,
- access?: CrawlerAccess | null,
+ options: {
+ /** Crawler-access headers for the audited host, when the org has one. */
+ access?: CrawlerAccess | null;
+ render?: (url: string) => Promise<RenderedPage>;
+ } = {},
): Promise<CrawledPageResult | null> {
+ const { access, render } = options;
const startTime = Date.now();
try {
const fetched = await fetchPage(url, throttle, access);
if (!fetched) return null;
const { response, responseTimeMs, rateLimited } = fetched;
- const statusCode = response.status;
+ let statusCode = response.status;
const xRobotsTag = response.headers.get("x-robots-tag");
const headerCanonicalUrl = parseLinkHeaderCanonical(
response.headers.get("link"),
@@ -149,13 +123,37 @@ export async function crawlPage(
const isHtml = contentType.includes("text/html");
// Cap what we read: the first 1 MiB still contains the SEO metadata and
// navigation needed by the audit in normal documents.
- const body = isHtml ? await readTextUpTo(response, MAX_HTML_BYTES) : "";
- const fetchClass = classifyFetch(
+ let body = isHtml ? await readTextUpTo(response, MAX_HTML_BYTES) : "";
+ let fetchClass = classifyFetch(
statusCode,
- response.headers,
+ Boolean(response.headers.get("cf-mitigated")),
body.slice(0, 4_000),
);
+ // Rendering replaces the body of a readable HTML page, or of a bot
+ // challenge, with what the browser loaded. Redirects, non-HTML files,
+ // origin errors, login walls and rate limits keep their existing paths.
+ // The direct response's timing and headers stay authoritative.
+ const challenged = fetchClass === "blocked" && statusCode !== 401;
+ if (
+ render &&
+ isHtml &&
+ (challenged || (fetchClass === "ok" && statusCode < 400))
+ ) {
+ try {
+ const page = await render(url);
+ body = page.html;
+ // A challenge's status was never the page's. Browser Run reports the
+ // status it loaded; Context returns only pages that loaded.
+ if (challenged) statusCode = page.status ?? 200;
+ // The renderer can be challenged where the direct fetch was not.
+ fetchClass = classifyFetch(statusCode, false, body.slice(0, 4_000));
+ } catch (error) {
+ // A challenge that neither renderer passed stays blocked.
+ if (!challenged) throw error;
+ }
+ }
+
if (!isHtml || fetchClass !== "ok" || statusCode >= 400) {
return emptyPageResult({
url,
@@ -180,6 +178,9 @@ export async function crawlPage(
// not just when an audit actually crawls.
const { analyzeHtml } = await import("@/server/lib/audit/page-analyzer");
const analysis = analyzeHtml(body, url, statusCode, responseTimeMs);
+ // Rendered HTML can still be the loading shell (a weak render), so the
+ // same check applies whether or not the page was rendered.
+ const javascriptShell = analysis.javascriptShell === true;
const robotsDirectives = [analysis.robotsMeta, xRobotsTag]
.filter(Boolean)
.join(",")
@@ -216,10 +217,12 @@ export async function crawlPage(
h6Count: headingCount(6),
headingOrder: analysis.headingOrder,
wordCount: analysis.wordCount,
- contentHash: analysis.bodyText
- ? await sha256Hex(analysis.bodyText)
- : null,
+ contentHash:
+ analysis.bodyText && !javascriptShell
+ ? await sha256Hex(analysis.bodyText)
+ : null,
isHtml: true,
+ javascriptShell,
htmlBytes: body.length,
rateLimited,
imagesTotal: analysis.images.length,
@@ -256,38 +259,6 @@ export async function crawlPage(
}
}
-async function readTextUpTo(response: Response, maxBytes: number) {
- if (!response.body) return "";
-
- const reader = response.body.getReader();
- const decoder = new TextDecoder();
- const parts: string[] = [];
- let bytesRead = 0;
-
- try {
- while (bytesRead < maxBytes) {
- const { done, value } = await reader.read();
- if (done) break;
-
- const remaining = maxBytes - bytesRead;
- const chunk =
- value.byteLength > remaining ? value.subarray(0, remaining) : value;
- bytesRead += chunk.byteLength;
- parts.push(decoder.decode(chunk, { stream: true }));
-
- if (bytesRead >= maxBytes) {
- await reader.cancel();
- break;
- }
- }
- } finally {
- reader.releaseLock();
- }
-
- parts.push(decoder.decode());
- return parts.join("");
-}
-
function emptyPageResult(input: {
url: string;
statusCode: number;
diff --git a/src/server/workflows/site-audit-workflow-rendering.test.ts b/src/server/workflows/site-audit-workflow-rendering.test.ts
new file mode 100644
index 00000000..8e3ad633
--- /dev/null
+++ b/src/server/workflows/site-audit-workflow-rendering.test.ts
@@ -0,0 +1,147 @@
+import { describe, expect, it, vi } from "vitest";
+import { createCrawlThrottle } from "@/server/lib/audit/crawl-throttle";
+import { crawlPage } from "@/server/workflows/site-audit-workflow-helpers";
+
+const PAGE_URL = "https://example.com/page";
+const PAGE_HTML =
+ "<html><head><title>A page</title></head><body><h1>A page</h1></body></html>";
+// What SiteGround's bot protection answers a datacenter crawler, with a 202.
+const SITEGROUND_CHALLENGE =
+ '<html><head><meta http-equiv="refresh" content="0;/.well-known/sgcaptcha/?r=%2Fpage"></meta></head></html>';
+function stubFetch({
+ status,
+ body = PAGE_HTML,
+ headers = {},
+}: {
+ status: number;
+ body?: string;
+ headers?: Record<string, string>;
+}) {
+ return vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response(body, {
+ status,
+ headers: {
+ "content-type": "text/html",
+ "x-robots-tag": "noindex",
+ ...headers,
+ },
+ }),
+ );
+}
+function crawl(render?: ReturnType<typeof rendered>) {
+ return crawlPage(
+ PAGE_URL,
+ 0,
+ false,
+ createCrawlThrottle(Date.now() + 90_000),
+ { render },
+ );
+}
+const renderedHtml =
+ '<html><head><title>Rendered title</title></head><body><h1>Loaded heading</h1><p>These words loaded through JavaScript.</p><a href="/discovered">Next page</a></body></html>';
+function rendered(html = renderedHtml, status: number | null = 200) {
+ return vi.fn().mockResolvedValue({ html, status });
+}
+
+describe("crawlPage with JavaScript rendering", () => {
+ it("analyzes rendered words, metadata and links while keeping the direct response's status and headers", async () => {
+ stubFetch({ status: 200 });
+ const page = await crawl(rendered());
+ expect(page).toMatchObject({
+ title: "Rendered title",
+ h1Count: 1,
+ statusCode: 200,
+ fetchClass: "ok",
+ isIndexable: false,
+ });
+ expect(page?.wordCount).toBeGreaterThan(5);
+ expect(page?.links).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ targetUrl: "https://example.com/discovered",
+ }),
+ ]),
+ );
+ });
+
+ it("flags an app shell, rendered or not, and clears the warning when rendered content is available", async () => {
+ const shell =
+ '<div id="root">Loading...</div><script src="/app.js"></script>';
+ vi.spyOn(globalThis, "fetch").mockImplementation(
+ async () =>
+ new Response(shell, { headers: { "content-type": "text/html" } }),
+ );
+ expect(await crawl()).toMatchObject({
+ javascriptShell: true,
+ contentHash: null,
+ });
+ expect(await crawl(rendered(shell))).toMatchObject({
+ javascriptShell: true,
+ });
+ expect(await crawl(rendered())).toMatchObject({ javascriptShell: false });
+ });
+
+ it("does not analyze a challenge page returned by the renderer", async () => {
+ stubFetch({ status: 200 });
+ expect(
+ await crawl(rendered("<title>Just a moment...</title>")),
+ ).toMatchObject({ statusCode: 200, fetchClass: "blocked", wordCount: 0 });
+ });
+
+ it.each([
+ { status: 202, body: SITEGROUND_CHALLENGE },
+ { status: 403, headers: { "cf-mitigated": "challenge" } },
+ ])(
+ "renders a page behind a $status bot challenge as the page it loaded",
+ async (response) => {
+ stubFetch(response);
+ // Context reports no status; a page it returns is one that loaded.
+ expect(await crawl(rendered(renderedHtml, null))).toMatchObject({
+ title: "Rendered title",
+ statusCode: 200,
+ fetchClass: "ok",
+ });
+ },
+ );
+
+ it("keeps a challenge that no renderer passed blocked, not failed", async () => {
+ stubFetch({ status: 202, body: SITEGROUND_CHALLENGE });
+ const render = rendered();
+ render.mockRejectedValue(new Error("Unable to render this page"));
+ expect(await crawl(render)).toMatchObject({
+ statusCode: 202,
+ fetchClass: "blocked",
+ });
+ });
+
+ it("marks SiteGround's challenge blocked instead of auditing it when rendering is off", async () => {
+ stubFetch({ status: 202, body: SITEGROUND_CHALLENGE });
+ expect(await crawl()).toMatchObject({
+ statusCode: 202,
+ fetchClass: "blocked",
+ wordCount: 0,
+ });
+ });
+
+ it.each([301, 401, 404, 500])(
+ "does not render a direct HTTP %s",
+ async (status) => {
+ stubFetch({ status });
+ const render = rendered();
+ await crawl(render);
+ expect(render).not.toHaveBeenCalled();
+ },
+ );
+
+ it("keeps a failed render as an unread page rather than auditing the HTML shell", async () => {
+ stubFetch({ status: 200 });
+ const render = rendered();
+ render.mockRejectedValue(new Error("Unable to render this page"));
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ expect(await crawl(render)).toMatchObject({
+ fetchClass: "error",
+ isHtml: false,
+ wordCount: 0,
+ });
+ });
+});
diff --git a/src/server/workflows/siteAuditWorkflowCrawl.test.ts b/src/server/workflows/siteAuditWorkflowCrawl.test.ts
index 93cd3a74..47f1db49 100644
--- a/src/server/workflows/siteAuditWorkflowCrawl.test.ts
+++ b/src/server/workflows/siteAuditWorkflowCrawl.test.ts
@@ -14,6 +14,13 @@ const mocks = vi.hoisted(() => ({
sleepUntil: vi.fn(),
getCrawlThrottle: vi.fn(),
saveCrawlThrottle: vi.fn(),
+ renderPage: vi.fn<typeof RenderedPageService.renderPage>(),
+}));
+vi.mock("cloudflare:workers", () => ({
+ env: { CONTEXT_API_KEY: "context-test-key" },
+}));
+vi.mock("@/server/lib/audit/rendered-page", () => ({
+ RenderedPageService: { renderPage: mocks.renderPage },
}));
vi.mock("cloudflare:workflows", () => ({
NonRetryableError: class extends Error {},
@@ -38,11 +45,13 @@ vi.mock("@/server/lib/audit/ids", () => ({
import { runCrawlPhase } from "@/server/workflows/siteAuditWorkflowCrawl";
import { parseRobotsTxt } from "@/server/lib/audit/discovery";
+import type { RenderedPageService } from "@/server/lib/audit/rendered-page";
const ORIGIN = "https://example.com";
const HTML = "<html><title>A page</title><body><h1>A page</h1></body></html>";
let saved: CrawledPageResult[];
let urls: string[];
+let renderUsage: { cloudflareAttempts: number; contextCredits: number };
beforeEach(async () => {
// Load the lazy HTML parser before advancing the fake network clock.
@@ -50,6 +59,7 @@ beforeEach(async () => {
vi.useFakeTimers();
vi.setSystemTime(0);
saved = [];
+ renderUsage = { cloudflareAttempts: 0, contextCredits: 0 };
let checkpoint: unknown;
mocks.getCrawlThrottle.mockImplementation(async () =>
structuredClone(checkpoint),
@@ -94,7 +104,7 @@ afterEach(() => {
vi.useRealTimers();
});
-function crawl(maxPages = 100) {
+function crawl(maxPages = 100, renderJavaScript = false) {
urls = Array.from({ length: maxPages }, (_, i) => `${ORIGIN}/${i}`);
return runCrawlPhase(
{
@@ -109,7 +119,9 @@ function crawl(maxPages = 100) {
origin: ORIGIN,
maxPages,
seededCount: maxPages,
+ renderJavaScript,
robots: parseRobotsTxt(ORIGIN, ""),
+ renderUsage,
},
);
}
@@ -286,3 +298,22 @@ describe("crawl pacing and cooldowns", () => {
expect(mocks.releaseUrls.mock.calls[0][0]).toHaveLength(99);
});
});
+
+describe("rendering usage", () => {
+ it("sums what every chunk rendered for the audit's one settlement", async () => {
+ serve(() => 200);
+ mocks.renderPage.mockImplementation(async (_url, { usage }) => {
+ usage.cloudflareAttempts += 1;
+ usage.contextCredits += 1;
+ return { html: HTML, status: 200 };
+ });
+ // 250 pages take two chunks of at most 200.
+ const run = crawl(250, true);
+ await vi.runAllTimersAsync();
+ await run;
+ expect(renderUsage).toEqual({
+ cloudflareAttempts: 250,
+ contextCredits: 250,
+ });
+ });
+});
diff --git a/src/server/workflows/siteAuditWorkflowCrawl.ts b/src/server/workflows/siteAuditWorkflowCrawl.ts
index 2fbfbced..75dd09a8 100644
--- a/src/server/workflows/siteAuditWorkflowCrawl.ts
+++ b/src/server/workflows/siteAuditWorkflowCrawl.ts
@@ -1,4 +1,4 @@
-import type { WorkflowStep } from "cloudflare:workers";
+import { env, type WorkflowStep } from "cloudflare:workers";
import { NonRetryableError } from "cloudflare:workflows";
import type { RobotsResult } from "@/server/lib/audit/discovery";
import type { CrawledPageResult } from "@/server/lib/audit/types";
@@ -25,6 +25,7 @@ import {
type CrawlThrottleState,
} from "@/server/lib/audit/crawl-throttle";
import { crawlPage } from "@/server/workflows/site-audit-workflow-helpers";
+import type { RenderUsage } from "@/shared/audit-rendering";
import type { CrawlerAccess } from "@/shared/crawler-access";
import { pgStep } from "@/server/workflows/pgStep";
import { CRAWL_CHUNK_STEP } from "@/server/workflows/auditStepConfigs";
@@ -92,6 +93,12 @@ type CrawlPhaseParams = {
robots: RobotsResult;
/** Frontier size after discovery seeding (from the discover-urls step). */
seededCount: number;
+ renderJavaScript?: boolean;
+ /**
+ * Rendering totals across chunks. Mutated as each chunk step returns, so a
+ * failed audit can still settle what its completed chunks rendered.
+ */
+ renderUsage: RenderUsage;
/** Crawler-access headers for the audited host, when the org has one. */
access?: CrawlerAccess | null;
};
@@ -138,6 +145,10 @@ export async function runCrawlPhase(
// with up-to-date scratchpad totals) — finalize must not see stale ones.
attemptedTotal = result.attempted;
pending = result.pending;
+ params.renderUsage.cloudflareAttempts +=
+ result.renderUsage?.cloudflareAttempts ?? 0;
+ params.renderUsage.contextCredits +=
+ result.renderUsage?.contextCredits ?? 0;
if (result.rateLimited) {
return {
pagesCrawled: attemptedTotal,
@@ -182,6 +193,7 @@ async function runCrawlChunk(
rateLimited?: boolean;
throttleState?: CrawlThrottleState;
resumeAt?: number;
+ renderUsage?: RenderUsage;
}> {
const { auditId, workflowInstanceId, origin, maxPages, robots, chunkNo } =
input;
@@ -283,13 +295,29 @@ async function runCrawlChunk(
});
};
+ // This attempt's rendering counts, returned in the step result. The audit's
+ // credit lock is settled once, when the audit ends.
+ const renderUsage: RenderUsage = { cloudflareAttempts: 0, contextCredits: 0 };
+ const render = input.renderJavaScript
+ ? async (url: string) => {
+ const { RenderedPageService } =
+ await import("@/server/lib/audit/rendered-page");
+ return RenderedPageService.renderPage(url, {
+ browser: env.BROWSER,
+ contextApiKey: env.CONTEXT_API_KEY,
+ auditId,
+ usage: renderUsage,
+ });
+ }
+ : undefined;
+
const launch = (entry: ClaimedUrl) => {
const promise = crawlPage(
entry.url,
entry.depth,
entry.inSitemap,
throttle,
- input.access,
+ { access: input.access, render },
)
.then((page) => {
if (!page) {
@@ -367,6 +395,7 @@ async function runCrawlChunk(
throttleState.pausedUntil > Date.now()
? throttleState.pausedUntil
: undefined,
+ renderUsage,
};
}
diff --git a/src/server/workflows/siteAuditWorkflowPhases.test.ts b/src/server/workflows/siteAuditWorkflowPhases.test.ts
index e6cd67cb..5ff6d520 100644
--- a/src/server/workflows/siteAuditWorkflowPhases.test.ts
+++ b/src/server/workflows/siteAuditWorkflowPhases.test.ts
@@ -37,12 +37,18 @@ vi.mock("@/server/features/audit/repositories/AuditRepository", () => ({
getPagesForAudit: getPagesForAuditMock,
insertLighthouseResults: insertLighthouseResultsMock,
updateAuditProgress: updateAuditProgressMock,
+ hasPagesForAudit: vi.fn().mockResolvedValue(true),
+ insertIssues: vi.fn(),
+ countPagesByFetchClass: vi.fn().mockResolvedValue(0),
+ completeAudit: vi.fn(),
},
}));
vi.mock("@/server/features/audit/AuditScratchpad", () => ({
getAuditScratchpad: vi.fn(),
}));
-vi.mock("@/server/lib/audit/progress-kv", () => ({ AuditProgressKV: {} }));
+vi.mock("@/server/lib/audit/progress-kv", () => ({
+ AuditProgressKV: { clear: vi.fn() },
+}));
vi.mock("@/server/lib/audit/discovery", () => ({
discoverUrls: vi.fn(),
parseRobotsTxt: vi.fn(),
@@ -56,7 +62,14 @@ vi.mock("@/server/workflows/siteAuditWorkflowCrawl", () => ({
}));
vi.mock("@/server/workflows/pgStep", () => ({ pgStep: pgStepMock }));
-import { runLighthousePhase } from "@/server/workflows/siteAuditWorkflowPhases";
+import {
+ runAuditPhases,
+ runLighthousePhase,
+} from "@/server/workflows/siteAuditWorkflowPhases";
+import { AuditRepository } from "@/server/features/audit/repositories/AuditRepository";
+import { getAuditScratchpad } from "@/server/features/audit/AuditScratchpad";
+import { runCrawlPhase } from "@/server/workflows/siteAuditWorkflowCrawl";
+import { runMultipageChecks } from "@/server/lib/audit/issues/multipage";
const PHASE_PARAMS = {
auditId: "audit-1",
@@ -192,3 +205,52 @@ describe("runLighthousePhase", () => {
);
});
});
+
+describe("app-shell crawl coverage", () => {
+ it.each([false, true])(
+ "allows orphan checks only without unread app shells (shells=%s)",
+ async (hasShells) => {
+ vi.mocked(AuditRepository.hasPagesForAudit).mockResolvedValue(true);
+ vi.mocked(runCrawlPhase).mockResolvedValue({
+ pagesCrawled: 2,
+ completed: true,
+ });
+ vi.mocked(runMultipageChecks).mockResolvedValue({
+ issues: [],
+ hasUnreadShells: hasShells,
+ });
+ const finalize = vi
+ .fn()
+ .mockResolvedValue({ brokenLinks: [], orphanPages: [] });
+ // Only these two scratchpad methods are reached after mocked discovery/crawl.
+ // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
+ vi.mocked(getAuditScratchpad).mockReturnValue({
+ runFinalizeChecks: finalize,
+ destroy: vi.fn(),
+ } as unknown as ReturnType<typeof getAuditScratchpad>);
+ pgStepMock.mockImplementation(
+ async (
+ _step: unknown,
+ name: string,
+ _config: unknown,
+ callback: () => Promise<unknown>,
+ ) => {
+ if (name === "discover-urls-v2")
+ return { robotsText: "", seededCount: 2 };
+ return callback();
+ },
+ );
+ // pgStep is mocked, so no WorkflowStep implementation is needed.
+ // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
+ await runAuditPhases({} as never, {
+ ...PHASE_PARAMS,
+ config: { maxPages: 50, lighthouseStrategy: "none" },
+ renderUsage: { cloudflareAttempts: 0, contextCredits: 0 },
+ });
+ expect(finalize).toHaveBeenCalledWith({
+ startUrl: "https://example.com/",
+ crawlCompleted: !hasShells,
+ });
+ },
+ );
+});
diff --git a/src/server/workflows/siteAuditWorkflowPhases.ts b/src/server/workflows/siteAuditWorkflowPhases.ts
index 508e76f5..a677a196 100644
--- a/src/server/workflows/siteAuditWorkflowPhases.ts
+++ b/src/server/workflows/siteAuditWorkflowPhases.ts
@@ -20,6 +20,7 @@ import { runMultipageChecks } from "@/server/lib/audit/issues/multipage";
import type { DetectedIssue } from "@/server/lib/audit/issues/page-reporters";
import type { AuditConfig } from "@/server/lib/audit/types";
import type { CrawlerAccess } from "@/shared/crawler-access";
+import type { RenderUsage } from "@/shared/audit-rendering";
import { captureServerEvent } from "@/server/lib/posthog";
import {
runCrawlPhase,
@@ -51,6 +52,7 @@ type AuditPhasesParams = {
startUrl: string;
config: AuditConfig;
access?: CrawlerAccess | null;
+ renderUsage: RenderUsage;
};
export async function runAuditPhases(
@@ -65,6 +67,7 @@ export async function runAuditPhases(
startUrl,
config,
access,
+ renderUsage,
} = params;
const origin = getOrigin(startUrl);
const maxPages = config.maxPages;
@@ -88,6 +91,8 @@ export async function runAuditPhases(
maxPages,
robots,
seededCount: discovery.seededCount,
+ renderJavaScript: config.renderJavaScript,
+ renderUsage,
access,
});
await runLighthousePhase(step, {
@@ -297,7 +302,7 @@ async function selectLighthousePages(params: {
const crawledPages = await AuditRepository.getPagesForAudit(auditId);
const sample = selectLighthouseSample(
crawledPages.map((page) => ({
- url: page.url,
+ ...page,
statusCode: page.statusCode ?? 0,
})),
startUrl,
@@ -357,14 +362,17 @@ async function finalizeAudit(args: {
const checksStartedAt = Date.now();
console.info("Audit finalization started", { auditId });
- const issues = await runMultipageChecks({ auditId });
+ const { issues, hasUnreadShells } = await runMultipageChecks({ auditId });
console.info("Audit multipage checks completed", {
auditId,
durationMs: Date.now() - checksStartedAt,
issueCount: issues.length,
});
const linksStartedAt = Date.now();
- const linkIssues = await runScratchpadLinkChecks(auditId, startUrl, crawl);
+ const linkIssues = await runScratchpadLinkChecks(auditId, startUrl, {
+ ...crawl,
+ completed: crawl.completed && !hasUnreadShells,
+ });
console.info("Audit link checks completed", {
auditId,
durationMs: Date.now() - linksStartedAt,
diff --git a/src/serverFunctions/audit.ts b/src/serverFunctions/audit.ts
index afe5a28a..3692f057 100644
--- a/src/serverFunctions/audit.ts
+++ b/src/serverFunctions/audit.ts
@@ -1,3 +1,4 @@
+import { isAuditRenderingAllowed } from "@/server/lib/audit/rendering-policy";
import { createServerFn } from "@tanstack/react-start";
import { waitUntil } from "cloudflare:workers";
import { requireOrgPermission } from "@/server/auth/org-gate";
@@ -27,6 +28,7 @@ export const startAudit = createServerFn({ method: "POST" })
maxPages: data.maxPages,
lighthouseStrategy: data.lighthouseStrategy,
limitTier,
+ renderJavaScript: data.renderJavaScript,
});
waitUntil(
@@ -84,3 +86,10 @@ export const deleteAudit = createServerFn({ method: "POST" })
await AuditService.remove(data.auditId, context.projectId);
return { success: true };
});
+
+export const getAuditCapabilities = createServerFn({ method: "POST" })
+ .middleware(requireProjectContext)
+ .validator(getAuditHistorySchema)
+ .handler(async () => ({
+ canRenderJavaScript: await isAuditRenderingAllowed(),
+ }));
diff --git a/src/shared/audit-issues.ts b/src/shared/audit-issues.ts
index 08b05cdb..b0e761c9 100644
--- a/src/shared/audit-issues.ts
+++ b/src/shared/audit-issues.ts
@@ -24,6 +24,14 @@ export const AUDIT_ISSUE_TYPES = {
howToFix:
'If you own this site, allowlist the "OpenSEO-Audit" user agent in your WAF/bot-protection settings (on Cloudflare: a WAF custom rule that skips bot protection when the user agent contains "OpenSEO-Audit"; on some free tiers you may need to relax bot protection). Then re-run the audit. On Shopify, use Crawler access instead (Online Store → Preferences → Crawler access) and paste the signature into OpenSEO under Settings → Crawler access.',
},
+ "javascript-rendering-suspected": {
+ severity: "warning",
+ title: "Content may require JavaScript",
+ explanation:
+ "The page's HTML contains a JavaScript app container with very little readable content and no headings, links, or images. The page may load its content in the browser, or it was still loading when rendered. Content checks were skipped because this HTML may not represent the complete page.",
+ howToFix:
+ 'If this audit did not render JavaScript, start a new audit with "Render JavaScript" enabled to check the loaded content. For reliable crawling, serve important content and navigation in the initial HTML using server-side rendering or prerendering. This warning does not prove that search engines cannot index the page.',
+ },
"rate-limited-page": {
severity: "warning",
title: "Rate limited (429)",
diff --git a/src/shared/audit-limits.ts b/src/shared/audit-limits.ts
index 0cc2b4f8..9d1f7610 100644
--- a/src/shared/audit-limits.ts
+++ b/src/shared/audit-limits.ts
@@ -4,3 +4,6 @@ export const MIN_AUDIT_PAGES = 10;
export const DEFAULT_AUDIT_PAGES = 50;
export const FREE_MAX_AUDIT_PAGES = 50;
export const PAID_MAX_AUDIT_PAGES = 10_000;
+// A rendered audit's credit hold is an Autumn lock, which lasts at most 24
+// hours. This keeps a rendered crawl well inside that window.
+export const RENDERED_MAX_AUDIT_PAGES = 1_000;
diff --git a/src/shared/audit-rendering.ts b/src/shared/audit-rendering.ts
new file mode 100644
index 00000000..29ec3b47
--- /dev/null
+++ b/src/shared/audit-rendering.ts
@@ -0,0 +1,65 @@
+import {
+ autumnSeoDataCreditsToUsd,
+ creditsForProviderUsd,
+} from "@/shared/billing";
+
+// Cloudflare Browser Run bills browser time at $0.09 an hour. Every attempt is
+// billed as its full timeout, not its measured time, so one attempt has one
+// fixed price and the low end of the estimate is exact.
+export const CLOUDFLARE_RENDER_TIMEOUT_MS = 20_000;
+const CLOUDFLARE_USD_PER_BROWSER_HOUR = 0.09;
+const CLOUDFLARE_USD_PER_ATTEMPT =
+ (CLOUDFLARE_RENDER_TIMEOUT_MS / 3_600_000) * CLOUDFLARE_USD_PER_BROWSER_HOUR;
+// Context.dev list price on the Developer plan. One scrape is one credit.
+const CONTEXT_USD_PER_CREDIT = 0.0025;
+
+/** Provider units a rendered audit used, counted per crawl chunk. */
+export type RenderUsage = {
+ cloudflareAttempts: number;
+ contextCredits: number;
+};
+
+export function renderUsageCredits(usage: RenderUsage): number {
+ return creditsForProviderUsd(
+ usage.cloudflareAttempts * CLOUDFLARE_USD_PER_ATTEMPT +
+ usage.contextCredits * CONTEXT_USD_PER_CREDIT,
+ );
+}
+
+/**
+ * Usage-credit range for rendering up to `maxPages` pages. The low end renders
+ * every page on Cloudflare. The high end is every page falling back to Context
+ * after its Cloudflare attempt, which is also what a hosted audit reserves.
+ */
+export function estimateRenderingCredits(maxPages: number) {
+ return {
+ low: renderUsageCredits({
+ cloudflareAttempts: maxPages,
+ contextCredits: 0,
+ }),
+ high: renderUsageCredits({
+ cloudflareAttempts: maxPages,
+ contextCredits: maxPages,
+ }),
+ };
+}
+
+/**
+ * Usage credits as the dollars users see everywhere else. Rounded up to the
+ * cent, so an account holding the shown amount always covers the hold.
+ */
+function formatRenderingUsd(credits: number) {
+ const cents = Math.ceil(autumnSeoDataCreditsToUsd(credits * 100));
+ return `$${(cents / 100).toFixed(2)}`;
+}
+
+/** Why a hosted account cannot start a rendered audit of `maxPages` pages. */
+export function renderingCreditsNeededText(maxPages: number) {
+ const { high } = estimateRenderingCredits(maxPages);
+ return `Rendering up to ${maxPages.toLocaleString("en-US")} pages needs ${formatRenderingUsd(high)} of credits available. Lower the page limit or add credits.`;
+}
+
+export function renderingEstimateText(maxPages: number) {
+ const { low, high } = estimateRenderingCredits(maxPages);
+ return `Estimated ${formatRenderingUsd(low)} to ${formatRenderingUsd(high)} for up to ${maxPages.toLocaleString("en-US")} pages. Sites with aggressive bot detection need our more capable renderer and cost more.`;
+}
diff --git a/src/types/schemas/audit.ts b/src/types/schemas/audit.ts
index e0e5dc8b..4f88ccaf 100644
--- a/src/types/schemas/audit.ts
+++ b/src/types/schemas/audit.ts
@@ -9,6 +9,7 @@ import {
export const startAuditSchema = z.object({
projectId: z.string().min(1),
+ renderJavaScript: z.boolean().optional().default(false),
startUrl: z.string().min(1, "URL is required").max(2048),
maxPages: z
.number()
diff --git a/vite.config.ts b/vite.config.ts
index 9b272824..bdd995ea 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -8,7 +8,7 @@ import { cloudflare } from "@cloudflare/vite-plugin";
import { devtools } from "@tanstack/devtools-vite";
import { leanWorkerBundle } from "./vite-plugin-lean-worker-bundle";
-export default defineConfig(({ mode }) => {
+export default defineConfig(({ mode, command }) => {
// Vitest sets mode to "test". Return a config without the Cloudflare and
// TanStack Start plugins so unit tests never boot workerd or the SSR dev
// server; only the tsconfig path alias is needed.
@@ -86,7 +86,17 @@ export default defineConfig(({ mode }) => {
// beside the main worker in dev and preview, with the app's
// cross-script SITE_AUDIT_WORKFLOW / AUDIT_SCRATCHPAD bindings
// resolved against it.
- auxiliaryWorkers: [{ configPath: "./wrangler.audit.jsonc" }],
+ // AUDIT_BROWSER_RENDERING=true attaches a remote Browser Run binding
+ // to it in dev, for rendered audits without a Context key.
+ auxiliaryWorkers: [
+ {
+ configPath: "./wrangler.audit.jsonc",
+ config:
+ command === "serve" && env.AUDIT_BROWSER_RENDERING === "true"
+ ? { browser: { binding: "BROWSER", remote: true } }
+ : {},
+ },
+ ],
}),
tsConfigPaths(),
tanstackStart(),
diff --git a/web/content/docs/self-hosting/cloudflare.md b/web/content/docs/self-hosting/cloudflare.md
index bb63bbf1..ee6a30b2 100644
--- a/web/content/docs/self-hosting/cloudflare.md
+++ b/web/content/docs/self-hosting/cloudflare.md
@@ -3,7 +3,7 @@ title: "Cloudflare Self-Hosting"
description: "Deploy OpenSEO to your own Cloudflare account for internet-facing, multi-device, or team use."
---
-Host OpenSEO on Cloudflare for internet-facing self-hosting across multiple devices or with your team. One deploy command provisions everything, including the Cloudflare Access login gate. Works on Cloudflare's free plan.
+Host OpenSEO on Cloudflare for internet-facing self-hosting across multiple devices or with your team. One deploy command provisions everything, including the Cloudflare Access login gate. Works on Cloudflare's free plan. JavaScript rendering in site audits needs a paid Workers plan.
## Prerequisites
@@ -99,5 +99,5 @@ pnpm deploy:selfhost --yes
## More guides on GitHub
-- [Operations](https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md): telemetry and other day-to-day tasks.
+- [Operations](https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md): JavaScript rendering for site audits, telemetry, and other day-to-day tasks.
- [Legacy deployments](https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_CLOUDFLARE_LEGACY.md): maintenance for installs created with the retired Deploy-button or manual Wrangler flows.