Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Let site owners verify the OpenSEO-Audit crawler instead of trusting its user agent (#1044)
Ben Senescu57d24eeb8f92
diff --git a/.github/workflows/deploy-production.yml b/.github/workflows/deploy-production.ymlindex 75681453..46f08ea1 100644--- a/.github/workflows/deploy-production.yml+++ b/.github/workflows/deploy-production.yml@@ -58,6 +58,7 @@ jobs:DATAFORSEO_API_KEY: ${{ secrets.DATAFORSEO_API_KEY }}BETTER_AUTH_SECRET: ${{ secrets.BETTER_AUTH_SECRET }}CRAWLER_ACCESS_SECRET: ${{ secrets.CRAWLER_ACCESS_SECRET }}+ WEB_BOT_AUTH_JWK: ${{ secrets.WEB_BOT_AUTH_JWK }}GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }}TURNSTILE_SECRET_KEY: ${{ secrets.TURNSTILE_SECRET_KEY }}LOOPS_API_KEY: ${{ secrets.LOOPS_API_KEY }}@@ -85,6 +86,7 @@ jobs:AUTUMN_SECRET_KEY AUTUMN_WEBHOOK_SECRET)optional=(CONTEXT_API_KEY OPENROUTER_API_KEY DUB_API_KEYMETA_CONVERSIONS_API_TOKEN GDPR_ERASURE_SECRET GOOGLE_MAPS_API_KEY+ WEB_BOT_AUTH_JWKLOOPS_PRODUCT_UPDATES_LIST_ID META_PIXEL_IDPOSTHOG_PUBLIC_KEY POSTHOG_HOST OPENROUTER_MODELOPENSEO_TELEMETRY_DISABLED)@@ -134,6 +136,7 @@ jobs:DATAFORSEO_API_KEY: ${{ secrets.DATAFORSEO_API_KEY }}BETTER_AUTH_SECRET: ${{ secrets.BETTER_AUTH_SECRET }}CRAWLER_ACCESS_SECRET: ${{ secrets.CRAWLER_ACCESS_SECRET }}+ WEB_BOT_AUTH_JWK: ${{ secrets.WEB_BOT_AUTH_JWK }}GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }}TURNSTILE_SECRET_KEY: ${{ secrets.TURNSTILE_SECRET_KEY }}LOOPS_API_KEY: ${{ secrets.LOOPS_API_KEY }}diff --git a/deploy/alchemy/alchemy.run.ts b/deploy/alchemy/alchemy.run.tsindex 7380b72c..ea824315 100644--- a/deploy/alchemy/alchemy.run.ts+++ b/deploy/alchemy/alchemy.run.ts@@ -257,6 +257,7 @@ const dataEnv = {BYPASS_EMAIL_VERIFICATION: optionalVar("BYPASS_EMAIL_VERIFICATION"),BETTER_AUTH_SECRET: optionalSecret("BETTER_AUTH_SECRET"),CRAWLER_ACCESS_SECRET: optionalSecret("CRAWLER_ACCESS_SECRET"),+ WEB_BOT_AUTH_JWK: optionalSecret("WEB_BOT_AUTH_JWK"),GOOGLE_CLIENT_ID: optionalVar("GOOGLE_CLIENT_ID"),GOOGLE_CLIENT_SECRET: optionalSecret("GOOGLE_CLIENT_SECRET"),GOOGLE_MAPS_API_KEY: optionalSecret("GOOGLE_MAPS_API_KEY"),@@ -389,10 +390,12 @@ export default Alchemy.Stack(// Deliberately NOT ...dataEnv: this worker crawls and parses// attacker-influenced HTML, so it gets only the secrets its code// path reads — DataForSEO (Lighthouse), Autumn (metering), PostHog- // (capture), CRAWLER_ACCESS_SECRET (Shopify signatures). No- // auth/OAuth/Loops/Turnstile secrets.+ // (capture), CRAWLER_ACCESS_SECRET (Shopify signatures),+ // WEB_BOT_AUTH_JWK (request signing). No auth/OAuth/Loops/Turnstile+ // secrets.BROWSER: Cloudflare.Browser(),CRAWLER_ACCESS_SECRET: dataEnv.CRAWLER_ACCESS_SECRET,+ WEB_BOT_AUTH_JWK: dataEnv.WEB_BOT_AUTH_JWK,CONTEXT_API_KEY: dataEnv.CONTEXT_API_KEY,DATAFORSEO_API_KEY: dataEnv.DATAFORSEO_API_KEY,AUTUMN_SECRET_KEY: dataEnv.AUTUMN_SECRET_KEY,diff --git a/docs/maintainers/production-deployment.md b/docs/maintainers/production-deployment.mdindex 22548610..330f4bc5 100644--- a/docs/maintainers/production-deployment.md+++ b/docs/maintainers/production-deployment.md@@ -34,6 +34,19 @@ deployment branches to `main`. Then add the following.| `META_CONVERSIONS_API_TOKEN` | Meta ad signup attribution (optional) || `GDPR_ERASURE_SECRET` | `scripts/erase-user-data.ts` endpoint (optional) || `GOOGLE_MAPS_API_KEY` | Local SEO basemap tiles (optional) |+| `WEB_BOT_AUTH_JWK` | Private Ed25519 JWK that signs site audit requests (optional) |++`WEB_BOT_AUTH_JWK` is one line of JSON (the whitespace check below rejects a+pretty-printed key). Generate it once with:++```sh+node -e 'crypto.subtle.generateKey({name:"Ed25519"},true,["sign","verify"]).then(k=>crypto.subtle.exportKey("jwk",k.privateKey)).then(j=>console.log(JSON.stringify({kty:j.kty,crv:j.crv,x:j.x,d:j.d})))'+```++The public half is served at `/.well-known/http-message-signatures-directory`,+which is the URL to give Cloudflare's Verified Bots submission form. Rotating+the key means re-submitting that form; Cloudflare matches signatures against+the keys it has on file.Copy the current production values from the live worker before the first run.Alchemy replaces the worker's complete var and secret set on every deploy, so adiff --git a/package.json b/package.jsonindex 09d22ad8..94ad02c5 100644--- a/package.json+++ b/package.json@@ -105,6 +105,7 @@"drizzle-orm": "^0.45.2","fast-xml-parser": "^5.4.1","htmlparser2": "^10.1.0",+ "http-message-sig": "0.3.0","jose": "^6.0.12","leaflet": "^1.9.4","lucide-react": "^0.542.0",@@ -125,6 +126,7 @@"takumi-js": "2.13.7","tldts": "^7.0.25","tw-animate-css": "^1.4.0",+ "web-bot-auth": "0.2.0","yaml": "^2.9.1","zod": "^4.1.12"},diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex db2a216a..3e222721 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -125,6 +125,9 @@ importers:htmlparser2:specifier: ^10.1.0version: 10.1.0+ http-message-sig:+ specifier: 0.3.0+ version: 0.3.0jose:specifier: ^6.0.12version: 6.1.3@@ -185,6 +188,9 @@ importers:tw-animate-css:specifier: ^1.4.0version: 1.4.0+ web-bot-auth:+ specifier: 0.2.0+ version: 0.2.0yaml:specifier: ^2.9.1version: 2.9.1@@ -4452,6 +4458,9 @@ packages:resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}engines: {node: '>= 0.8'}+ resolution: {integrity: sha512-ossX5ZDDCRD+YtMzryp3gCg+5wqLFes1RVChEFmEE9Bzbd49Ts2IIIvFnTst/mYWx0ivrxrTTPsIIKKJ07s7+w==}+resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==}engines: {node: '>=10.17.0'}@@ -4738,6 +4747,9 @@ packages:resolution: {integrity: sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==}+ resolution: {integrity: sha512-4m/gJEUQH8N2NfvZFjCL8/E+vlt0FlrmHoR4T93CEXQRkC64qwRi6oQri4/eqLVXqEqXYCss0+Q7pLx6vJBqzw==}+resolution: {integrity: sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==}@@ -6140,6 +6152,10 @@ packages:resolution: {integrity: sha512-ki4hZQfh5rX0QDLLkOCj+h+CVNkqmp/CMf8v8kZpkNVK6jGQooMytqzLZYUVYIZcFZ6yDB70EfD8POcFXiF5oA==}engines: {node: '>=18'}+ resolution: {integrity: sha512-4g5yxhlDMClRwCcfKfLeS7Z8yAVdOWGDADwm80Poh1iReU2KVKLGBlqwpHWJ2qovq0+ZIf1atAEO1eua2o9Rgg==}+ engines: {node: '>=18', npm: '>=6'}+resolution: {integrity: sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==}@@ -6539,6 +6555,9 @@ packages:resolution: {integrity: sha512-3hu+tD8YzSLGuFYtPRb48vdhKMi0KQV5sn+uWr8+7dMEq/2G/dtLrdDinkLjqq5TIbIBjYJ4Ax/n3YiaW7QM8A==}engines: {node: 20 || >=22}+ resolution: {integrity: sha512-3DJ72ZhWK4a3yCHCClF6q32g03X37DJlpyASYeBroGTRj/qFkHNcPwkESc3FLigjW6NOWF6MR+Hat9AfOqqtAQ==}+resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}engines: {node: '>= 8'}@@ -10668,6 +10687,10 @@ snapshots:statuses: 2.0.2toidentifier: 1.0.1+ dependencies:+ structured-headers: 2.0.3+@@ -10905,6 +10928,8 @@ snapshots:optionalDependencies:graceful-fs: 4.2.11+ [email protected]: {}+dependencies:lie: 3.3.0@@ -12639,6 +12664,8 @@ snapshots:dependencies:'@tokenizer/token': 0.3.0+ [email protected]: {}+dependencies:style-to-object: 1.0.14@@ -12981,6 +13008,12 @@ snapshots:+ dependencies:+ http-message-sig: 0.3.0+ jsonwebkey-thumbprint: 0.1.0+ structured-headers: 2.0.3+diff --git a/src/client/features/audit/results/ResultsView.tsx b/src/client/features/audit/results/ResultsView.tsxindex 234b8fd1..941f2d33 100644--- a/src/client/features/audit/results/ResultsView.tsx+++ b/src/client/features/audit/results/ResultsView.tsx@@ -130,7 +130,16 @@ export function ResultsView({? "The requested cooldown exceeded the audit time limit, so some URLs were left unvisited. This report is incomplete. ": "Pages that returned 429 Too Many Requests could not be audited. "}Re-run the audit after the rate limit resets, or ask the site owner- to allow the "OpenSEO-Audit" crawler.+ to allow the{" "}+ <a+ className="underline underline-offset-4"+ href="https://openseo.so/docs/crawler"+ target="_blank"+ rel="noreferrer"+ >+ OpenSEO-Audit crawler+ </a>+ .</AlertDescription></Alert>)}diff --git a/src/env.d.ts b/src/env.d.tsindex 7eded92f..0c6af286 100644--- a/src/env.d.ts+++ b/src/env.d.ts@@ -39,6 +39,9 @@ declare namespace Cloudflare {// Encrypts saved Shopify crawler signatures. Kept separate from// BETTER_AUTH_SECRET so the audit worker never holds the auth secret.CRAWLER_ACCESS_SECRET?: string;+ // Private Ed25519 JWK that signs site audit requests (Web Bot Auth). Hosted+ // only; unset sends unsigned requests.+ WEB_BOT_AUTH_JWK?: string;DATABASE_PROVIDER?: "d1" | "postgres";HYPERDRIVE?: {connectionString: string;diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.tsindex 5cc3e0ed..c10efea7 100644--- a/src/routeTree.gen.ts+++ b/src/routeTree.gen.ts@@ -16,6 +16,7 @@ import { Route as AuthErrorRouteImport } from './routes/auth-error'import { Route as ForgotPasswordRouteImport } from './routes/forgot-password'import { Route as ResetPasswordRouteImport } from './routes/reset-password'import { Route as VerifyEmailRouteImport } from './routes/verify-email'+import { Route as Char91DotwellKnownChar93HttpMessageSignaturesDirectoryRouteImport } from './routes/[.well-known]/http-message-signatures-directory'import { Route as Char91DotwellKnownChar93OpenaiAppsChallengeRouteImport } from './routes/[.well-known]/openai-apps-challenge'import { Route as AppIndexRouteImport } from './routes/_app/index'import { Route as AppAiRouteImport } from './routes/_app/ai'@@ -109,6 +110,12 @@ const VerifyEmailRoute = VerifyEmailRouteImport.update({path: '/verify-email',getParentRoute: () => rootRouteImport,} as any)+const Char91DotwellKnownChar93HttpMessageSignaturesDirectoryRoute =+ Char91DotwellKnownChar93HttpMessageSignaturesDirectoryRouteImport.update({+ id: '/.well-known/http-message-signatures-directory',+ path: '/.well-known/http-message-signatures-directory',+ getParentRoute: () => rootRouteImport,+ } as any)const Char91DotwellKnownChar93OpenaiAppsChallengeRoute =Char91DotwellKnownChar93OpenaiAppsChallengeRouteImport.update({id: '/.well-known/openai-apps-challenge',@@ -439,6 +446,7 @@ export interface FileRoutesByFullPath {'/forgot-password': typeof ForgotPasswordRoute'/reset-password': typeof ResetPasswordRoute'/verify-email': typeof VerifyEmailRoute+ '/.well-known/http-message-signatures-directory': typeof Char91DotwellKnownChar93HttpMessageSignaturesDirectoryRoute'/.well-known/openai-apps-challenge': typeof Char91DotwellKnownChar93OpenaiAppsChallengeRoute'/ai': typeof AppAiRoute'/billing': typeof AppBillingRoute@@ -505,6 +513,7 @@ export interface FileRoutesByTo {'/forgot-password': typeof ForgotPasswordRoute'/reset-password': typeof ResetPasswordRoute'/verify-email': typeof VerifyEmailRoute+ '/.well-known/http-message-signatures-directory': typeof Char91DotwellKnownChar93HttpMessageSignaturesDirectoryRoute'/.well-known/openai-apps-challenge': typeof Char91DotwellKnownChar93OpenaiAppsChallengeRoute'/ai': typeof AppAiRoute'/billing': typeof AppBillingRoute@@ -568,6 +577,7 @@ export interface FileRoutesById {'/forgot-password': typeof ForgotPasswordRoute'/reset-password': typeof ResetPasswordRoute'/verify-email': typeof VerifyEmailRoute+ '/.well-known/http-message-signatures-directory': typeof Char91DotwellKnownChar93HttpMessageSignaturesDirectoryRoute'/.well-known/openai-apps-challenge': typeof Char91DotwellKnownChar93OpenaiAppsChallengeRoute'/_app/ai': typeof AppAiRoute'/_app/billing': typeof AppBillingRoute@@ -637,6 +647,7 @@ export interface FileRouteTypes {| '/forgot-password'| '/reset-password'| '/verify-email'+ | '/.well-known/http-message-signatures-directory'| '/.well-known/openai-apps-challenge'| '/ai'| '/billing'@@ -703,6 +714,7 @@ export interface FileRouteTypes {| '/forgot-password'| '/reset-password'| '/verify-email'+ | '/.well-known/http-message-signatures-directory'| '/.well-known/openai-apps-challenge'| '/ai'| '/billing'@@ -765,6 +777,7 @@ export interface FileRouteTypes {| '/forgot-password'| '/reset-password'| '/verify-email'+ | '/.well-known/http-message-signatures-directory'| '/.well-known/openai-apps-challenge'| '/_app/ai'| '/_app/billing'@@ -835,6 +848,7 @@ export interface RootRouteChildren {ForgotPasswordRoute: typeof ForgotPasswordRouteResetPasswordRoute: typeof ResetPasswordRouteVerifyEmailRoute: typeof VerifyEmailRoute+ Char91DotwellKnownChar93HttpMessageSignaturesDirectoryRoute: typeof Char91DotwellKnownChar93HttpMessageSignaturesDirectoryRouteChar91DotwellKnownChar93OpenaiAppsChallengeRoute: typeof Char91DotwellKnownChar93OpenaiAppsChallengeRouteAcceptInvitationIdRoute: typeof AcceptInvitationIdRouteApiHealthRoute: typeof ApiHealthRoute@@ -901,6 +915,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof VerifyEmailRouteImportparentRoute: typeof rootRouteImport}+ '/.well-known/http-message-signatures-directory': {+ id: '/.well-known/http-message-signatures-directory'+ path: '/.well-known/http-message-signatures-directory'+ fullPath: '/.well-known/http-message-signatures-directory'+ preLoaderRoute: typeof Char91DotwellKnownChar93HttpMessageSignaturesDirectoryRouteImport+ parentRoute: typeof rootRouteImport+ }'/.well-known/openai-apps-challenge': {id: '/.well-known/openai-apps-challenge'path: '/.well-known/openai-apps-challenge'@@ -1523,6 +1544,8 @@ const rootRouteChildren: RootRouteChildren = {ForgotPasswordRoute: ForgotPasswordRoute,ResetPasswordRoute: ResetPasswordRoute,VerifyEmailRoute: VerifyEmailRoute,+ Char91DotwellKnownChar93HttpMessageSignaturesDirectoryRoute:+ Char91DotwellKnownChar93HttpMessageSignaturesDirectoryRoute,Char91DotwellKnownChar93OpenaiAppsChallengeRoute:Char91DotwellKnownChar93OpenaiAppsChallengeRoute,AcceptInvitationIdRoute: AcceptInvitationIdRoute,diff --git a/src/routes/[.well-known]/http-message-signatures-directory.ts b/src/routes/[.well-known]/http-message-signatures-directory.tsnew file mode 100644index 00000000..9c7ce86c--- /dev/null+++ b/src/routes/[.well-known]/http-message-signatures-directory.ts@@ -0,0 +1,14 @@+import { createFileRoute } from "@tanstack/react-router";+import { webBotAuthDirectoryResponse } from "@/server/lib/audit/web-bot-auth";++// Web Bot Auth key directory: the public key that verifies the site audit+// crawler's request signatures.+export const Route = createFileRoute(+ "/.well-known/http-message-signatures-directory",+)({+ server: {+ handlers: {+ GET: async ({ request }) => webBotAuthDirectoryResponse(request),+ },+ },+});diff --git a/src/server/lib/audit/discovery.test.ts b/src/server/lib/audit/discovery.test.tsindex 80e9585c..bb14c1a7 100644--- a/src/server/lib/audit/discovery.test.ts+++ b/src/server/lib/audit/discovery.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from "vitest";-import { discoverUrls } from "@/server/lib/audit/discovery";+import { discoverUrls, parseRobotsTxt } from "@/server/lib/audit/discovery";function sitemapXml(urls: string[]): string {const entries = urls.map((url) => `<url><loc>${url}</loc></url>`).join("");@@ -34,3 +34,15 @@ describe("discoverUrls", () => {expect(urls).toContain("https://example.com/");});});++describe("parseRobotsTxt", () => {+ it("applies an OpenSEO-Audit group over the wildcard group", () => {+ const robots = parseRobotsTxt(+ "https://example.com",+ "User-agent: *\nAllow: /\n\nUser-agent: OpenSEO-Audit\nDisallow: /private/",+ );++ expect(robots.isAllowed("https://example.com/private/page")).toBe(false);+ expect(robots.isAllowed("https://example.com/public")).toBe(true);+ });+});diff --git a/src/server/lib/audit/discovery.ts b/src/server/lib/audit/discovery.tsindex e42b7180..a12cd4d4 100644--- a/src/server/lib/audit/discovery.ts+++ b/src/server/lib/audit/discovery.ts@@ -5,7 +5,11 @@ import robotsParser from "robots-parser";import { XMLParser } from "fast-xml-parser";import { isSameOrigin, normalizeUrl } from "./url-utils";import { isCrawlableUrl } from "./url-policy";-import { crawlerHeadersFor, type CrawlerAccess } from "@/shared/crawler-access";+import type { CrawlerAccess } from "@/shared/crawler-access";+import {+ auditRequestHeaders,+ CRAWL_USER_AGENT,+} from "@/server/lib/audit/web-bot-auth";const SITEMAP_FETCH_TIMEOUT_MS = 15_000;// robots.txt is checkpointed as durable Workflow step state (~1MiB cap, shared@@ -74,10 +78,7 @@ async function fetchFollowingRedirects(let current = url;for (let hop = 0; hop <= MAX_DISCOVERY_REDIRECT_HOPS; hop++) {const response = await fetch(current, {- headers: {- "User-Agent": "OpenSEO-Audit/1.0",- ...crawlerHeadersFor(current, access),- },+ headers: await auditRequestHeaders(current, access),redirect: "manual",signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())),});@@ -113,7 +114,8 @@ export function parseRobotsTxt(const robots = robotsParser(`${origin}/robots.txt`, text);return {- isAllowed: (url: string) => robots.isAllowed(url) ?? true,+ // Our UA so an `OpenSEO-Audit` group wins over `*`.+ isAllowed: (url: string) => robots.isAllowed(url, CRAWL_USER_AGENT) ?? true,sitemapUrls: robots.getSitemaps(),};}diff --git a/src/server/lib/audit/url-policy.ts b/src/server/lib/audit/url-policy.tsindex 0b86e5b8..7709aa61 100644--- a/src/server/lib/audit/url-policy.ts+++ b/src/server/lib/audit/url-policy.ts@@ -1,5 +1,6 @@import { AppError } from "@/server/lib/errors";-import { crawlerHeadersFor, type CrawlerAccess } from "@/shared/crawler-access";+import type { CrawlerAccess } from "@/shared/crawler-access";+import { auditRequestHeaders } from "@/server/lib/audit/web-bot-auth";const BLOCKED_HOSTS = new Set(["localhost",@@ -282,10 +283,7 @@ export async function resolveStartUrlRedirects(response = await fetch(current, {method: "HEAD",redirect: "manual",- headers: {- "User-Agent": "OpenSEO-Audit/1.0",- ...crawlerHeadersFor(current, access),- },+ headers: await auditRequestHeaders(current, access),signal: AbortSignal.timeout(START_URL_PROBE_TIMEOUT_MS),});} catch {diff --git a/src/server/lib/audit/web-bot-auth.test.ts b/src/server/lib/audit/web-bot-auth.test.tsnew file mode 100644index 00000000..a334eb3c--- /dev/null+++ b/src/server/lib/audit/web-bot-auth.test.ts@@ -0,0 +1,76 @@+import { component, verifySignature } from "http-message-sig";+import { describe, expect, it, vi } from "vitest";+import { verify } from "web-bot-auth";+import { verifierFromJWK } from "web-bot-auth/crypto";+import {+ auditRequestHeaders,+ webBotAuthDirectoryResponse,+} from "@/server/lib/audit/web-bot-auth";+import { shopifyCrawlerHeaders } from "@/shared/crawler-access";++// Throwaway Ed25519 key generated for this test only.+vi.stubEnv(+ "WEB_BOT_AUTH_JWK",+ JSON.stringify({+ kty: "OKP",+ crv: "Ed25519",+ x: "glWMEy-lxqPQCnzI1tlvw2Dcdb-t_eKxsPBnrJGe1sI",+ d: "gKhzKRPN1zRoY7qGIrJOgIR3EAKc2z2or811liRtJPs",+ }),+);++describe("auditRequestHeaders", () => {+ it("signs requests with the key the signed directory publishes", async () => {+ const url = "https://example.com/page";+ const headers = await auditRequestHeaders(url, null);+ const directoryRequest = new Request(+ "https://app.openseo.so/.well-known/http-message-signatures-directory",+ );+ const directory = await webBotAuthDirectoryResponse(directoryRequest);+ const { keys } = await directory.json<{ keys: JsonWebKey[] }>();+ const verifier = await verifierFromJWK(keys[0]);++ expect(keys[0]).not.toHaveProperty("d");+ await expect(+ verify(new Request(url, { headers }), { resolver: () => verifier }),+ ).resolves.toMatchObject({+ signatureAgent: { uri: "https://app.openseo.so" },+ });+ // The directory itself is signed the way Cloudflare's verifier expects.+ await expect(+ verifySignature(+ {+ kind: "response",+ status: directory.status,+ fields: [...directory.headers].map(([name, value]) => ({+ name,+ value,+ })),+ request: directoryRequest,+ },+ {+ label: "binding0",+ policy: {+ algorithms: ["ed25519"],+ requiredComponents: [component("@authority", { req: true })],+ requiredParameters: ["keyid", "created", "expires", "tag"],+ validate: (signature) =>+ signature.parameters.tag === "http-message-signatures-directory",+ },+ resolveVerifier: () => verifier,+ },+ ),+ ).resolves.toBeDefined();+ });++ it("sends a store's Shopify signature instead of ours", async () => {+ const shopify = shopifyCrawlerHeaders("sig1=(...)", "sig1=:abc:");+ const headers = await auditRequestHeaders("https://store.com/", {+ host: "store.com",+ headers: shopify,+ expiresAt: null,+ });++ expect(headers).toEqual({ "User-Agent": "OpenSEO-Audit/1.0", ...shopify });+ });+});diff --git a/src/server/lib/audit/web-bot-auth.ts b/src/server/lib/audit/web-bot-auth.tsnew file mode 100644index 00000000..04b5aa3c--- /dev/null+++ b/src/server/lib/audit/web-bot-auth.ts@@ -0,0 +1,137 @@+/**+ * Web Bot Auth signing for the site audit crawler.+ *+ * Site owners behind Cloudflare (and other gatekeepers) can verify that a+ * request really came from OpenSEO instead of trusting the spoofable+ * User-Agent. Every crawler request carries an RFC 9421 signature made with our+ * Ed25519 key, and the public half is served from the key directory on the app+ * origin. Unset WEB_BOT_AUTH_JWK (self-hosting) sends unsigned requests.+ */+import { component, createSignature } from "http-message-sig";+import { sign, type WebBotSigner } from "web-bot-auth";+import { signerFromJWK } from "web-bot-auth/crypto";+import { z } from "zod";+import { getOptionalEnvValue } from "@/server/lib/runtime-env";+import { crawlerHeadersFor, type CrawlerAccess } from "@/shared/crawler-access";++export const CRAWL_USER_AGENT = "OpenSEO-Audit/1.0";++/** Where verifiers fetch our public key: `<origin>/.well-known/http-message-signatures-directory`. */+const SIGNATURE_AGENT_ORIGIN = "https://app.openseo.so";++const SIGNATURE_LIFETIME_MS = 60_000;++const ed25519PrivateJwk = z.object({+ kty: z.literal("OKP"),+ crv: z.literal("Ed25519"),+ x: z.string(),+ d: z.string(),+});++interface SigningKey {+ signer: WebBotSigner;+ publicJwk: { kty: "OKP"; crv: "Ed25519"; x: string };+}++let signingKeyPromise: Promise<SigningKey | null> | undefined;++/** Null when signing is off. A bad key must not take audits down: crawl unsigned. */+function getSigningKey(): Promise<SigningKey | null> {+ signingKeyPromise ??= loadSigningKey().catch(() => {+ // Not the error itself: a JSON.parse message quotes the text around the+ // bad token, which could be part of the private key.+ console.error("WEB_BOT_AUTH_JWK is unusable; crawling unsigned");+ return null;+ });+ return signingKeyPromise;+}++async function loadSigningKey(): Promise<SigningKey | null> {+ const jwkText = await getOptionalEnvValue("WEB_BOT_AUTH_JWK");+ if (!jwkText) return null;+ const jwk = ed25519PrivateJwk.parse(JSON.parse(jwkText));+ return {+ signer: await signerFromJWK(jwk),+ publicJwk: { kty: jwk.kty, crv: jwk.crv, x: jwk.x },+ };+}++/**+ * Headers for one crawler request to `url`. Shopify crawler access already+ * carries its own `Signature*` headers for that store, so ours are only added+ * when no crawler-access credential applies.+ */+export async function auditRequestHeaders(+ url: string,+ access: CrawlerAccess | null | undefined,+): Promise<Record<string, string>> {+ const headers: Record<string, string> = { "User-Agent": CRAWL_USER_AGENT };+ const accessHeaders = crawlerHeadersFor(url, access);+ if (Object.keys(accessHeaders).length > 0) {+ return { ...headers, ...accessHeaders };+ }++ const key = await getSigningKey();+ if (!key) return headers;++ // Structured-string form: the one Cloudflare verifies today.+ headers["Signature-Agent"] = `"${SIGNATURE_AGENT_ORIGIN}"`;+ const now = new Date();+ // Covers @authority and Signature-Agent only, so the method is irrelevant.+ const fields = await sign(+ {+ kind: "request",+ method: "GET",+ targetUri: url,+ fields: Object.entries(headers).map(([name, value]) => ({ name, value })),+ },+ {+ signer: key.signer,+ created: now,+ expires: new Date(now.getTime() + SIGNATURE_LIFETIME_MS),+ },+ );+ headers.Signature = fields.signature;+ headers["Signature-Input"] = fields.signatureInput;+ return headers;+}++/** The signed public key directory verifiers fetch, or 404 when signing is off. */+export async function webBotAuthDirectoryResponse(+ request: Request,+): Promise<Response> {+ const key = await getSigningKey();+ if (!key) return new Response("Not found", { status: 404 });++ const { signer } = key;+ const headers = new Headers({+ "content-type": "application/http-message-signatures-directory+json",+ "cache-control": "public, max-age=300",+ });+ const created = Math.floor(Date.now() / 1000);+ const fields = await createSignature(+ {+ kind: "response",+ status: 200,+ fields: [],+ request,+ },+ {+ label: "binding0",+ signer,+ components: [component("@authority", { req: true })],+ parameters: {+ created,+ expires: created + 3600,+ keyid: signer.keyid,+ alg: signer.algorithm,+ tag: "http-message-signatures-directory",+ },+ },+ );+ headers.set("Signature", fields.signature);+ headers.set("Signature-Input", fields.signatureInput);+ return new Response(JSON.stringify({ keys: [key.publicJwk] }), {+ headers,+ });+}diff --git a/src/server/workflows/site-audit-workflow-helpers.test.ts b/src/server/workflows/site-audit-workflow-helpers.test.tsindex e5f72367..30e9bfe6 100644--- a/src/server/workflows/site-audit-workflow-helpers.test.ts+++ b/src/server/workflows/site-audit-workflow-helpers.test.ts@@ -3,6 +3,10 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { createCrawlThrottle } from "@/server/lib/audit/crawl-throttle";import { crawlPage } from "@/server/workflows/site-audit-workflow-helpers";+// Resolves the request-signing env lookup instantly, so it can't race the+// fake timers below.+vi.mock("cloudflare:workers", () => ({ env: {} }));+const PAGE_URL = "https://example.com/page";const PAGE_HTML ="<html><head><title>A page</title></head><body><h1>A page</h1></body></html>";diff --git a/src/server/workflows/site-audit-workflow-helpers.ts b/src/server/workflows/site-audit-workflow-helpers.tsindex 35af939a..b2d47e34 100644--- a/src/server/workflows/site-audit-workflow-helpers.ts+++ b/src/server/workflows/site-audit-workflow-helpers.ts@@ -6,9 +6,8 @@ import type { PageFetchClass } from "@/shared/audit-fetch-class";import { sha256Hex } from "@/server/lib/audit/ids";import { normalizeUrl } from "@/server/lib/audit/url-utils";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";+import type { CrawlerAccess } from "@/shared/crawler-access";+import { auditRequestHeaders } from "@/server/lib/audit/web-bot-auth";/** Parse `Link: <url>; rel="canonical"` response headers. */function parseLinkHeaderCanonical(@@ -49,9 +48,8 @@ async function fetchPage(// to its canonical target instead of cycling back to its own source.const response = await fetch(url, {headers: {- "User-Agent": CRAWL_USER_AGENT,Accept: "text/html,application/xhtml+xml",- ...crawlerHeadersFor(url, access),+ ...(await auditRequestHeaders(url, access)),},redirect: "manual",signal: AbortSignal.timeout(15_000),diff --git a/src/shared/audit-issues.ts b/src/shared/audit-issues.tsindex b0e761c9..b6e1d2aa 100644--- a/src/shared/audit-issues.ts+++ b/src/shared/audit-issues.ts@@ -22,7 +22,7 @@ export const AUDIT_ISSUE_TYPES = {explanation:"The site returned a bot challenge or access denial (e.g. a Cloudflare challenge or a 403) instead of the page. We report this honestly rather than pretending the page is broken — but it means this page could not be audited, and other crawlers like search engines may face similar friction.",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.',+ '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. How to allow and verify the crawler: https://openseo.so/docs/crawler',},"javascript-rendering-suspected": {severity: "warning",@@ -38,7 +38,7 @@ export const AUDIT_ISSUE_TYPES = {explanation:"The server answered 429 Too Many Requests, so this page could not be audited. The crawler waits before retrying when the site's cooldown fits within the audit time limit.",howToFix:- 'Raise the rate limit for crawlers, or allowlist the "OpenSEO-Audit" user agent in your rate-limiting rules (on Cloudflare: a rate-limiting rule exception matching that user agent). Then re-run the audit. Re-running with fewer pages also helps if the limit is strict. On Shopify, use Crawler access instead (Online Store → Preferences → Crawler access) and paste the signature into OpenSEO under Settings → Crawler access.',+ 'Raise the rate limit for crawlers, or allowlist the "OpenSEO-Audit" user agent in your rate-limiting rules (on Cloudflare: a rate-limiting rule exception matching that user agent). Then re-run the audit. Re-running with fewer pages also helps if the limit is strict. On Shopify, use Crawler access instead (Online Store → Preferences → Crawler access) and paste the signature into OpenSEO under Settings → Crawler access. How to allow and verify the crawler: https://openseo.so/docs/crawler',},"crawl-rate-limited": {severity: "warning",@@ -46,7 +46,7 @@ export const AUDIT_ISSUE_TYPES = {explanation:"The site asked the crawler to wait longer than the audit time limit allowed. We stopped requesting pages. This report is incomplete; URLs we did not fetch are not recorded as broken or rate limited.",howToFix:- "Re-run the audit after the site's rate limit resets, or ask the site owner to allow the OpenSEO-Audit crawler. On Shopify, use Crawler access instead (Online Store → Preferences → Crawler access) and paste the signature into OpenSEO under Settings → Crawler access.",+ "Re-run the audit after the site's rate limit resets, or ask the site owner to allow the OpenSEO-Audit crawler (https://openseo.so/docs/crawler). On Shopify, use Crawler access instead (Online Store → Preferences → Crawler access) and paste the signature into OpenSEO under Settings → Crawler access.",},"server-error": {severity: "critical",diff --git a/web/content/docs/crawler.md b/web/content/docs/crawler.mdnew file mode 100644index 00000000..1438c337--- /dev/null+++ b/web/content/docs/crawler.md@@ -0,0 +1,46 @@+---+title: "OpenSEO-Audit crawler"+description: "What the OpenSEO site audit crawler does, how it identifies itself, and how to allow or block it."+---++OpenSEO-Audit is the crawler behind OpenSEO's site audits. It only visits a site when an OpenSEO user starts an audit of that site. It reads pages to check for SEO issues like broken links, missing titles, and redirect chains. It does not index content or collect training data for AI.++## How it identifies itself++Every request sends this user agent:++```+OpenSEO-Audit/1.0+```++Requests from OpenSEO's hosted app are also signed with [Web Bot Auth](https://developers.cloudflare.com/bots/reference/bot-verification/web-bot-auth/), an HTTP message signature standard. A user agent can be faked, but a signature can't. The public key is published at:++```+https://app.openseo.so/.well-known/http-message-signatures-directory+```++The crawler runs on Cloudflare Workers, so it has no fixed IP addresses. Use the signature to verify it instead of an IP list.++## robots.txt++An audit starts with one `HEAD` request to the start URL, following redirects, to find the site's real address. The crawler then reads `robots.txt` and skips any page it disallows. Rules for `OpenSEO-Audit` take priority over rules for `*`. To keep it out of your whole site:++```+User-agent: OpenSEO-Audit+Disallow: /+```++## Crawl rate++The crawler sends about one request per second to a site, and an audit fetches a limited number of pages, set by the user who starts it. When a site answers with `429 Too Many Requests`, the crawler slows down and follows the `Retry-After` header before trying again. If the site keeps asking it to wait, the audit stops early.++## Allowing the crawler through a firewall++If your firewall or bot protection blocks OpenSEO-Audit, allow requests whose user agent contains `OpenSEO-Audit`. On Cloudflare, create a WAF custom rule that skips bot protection for that user agent.++Self-hosted copies of OpenSEO send the same user agent but do not sign their requests.++Two optional audit features load pages another way, without the `OpenSEO-Audit` user agent or a signature:++- "Render JavaScript" loads pages in a headless browser, usually [Cloudflare Browser Run](https://developers.cloudflare.com/browser-run/).+- Lighthouse checks run from [DataForSEO](https://dataforseo.com/)'s servers with Lighthouse's own Chrome user agent.diff --git a/web/content/docs/meta.json b/web/content/docs/meta.jsonindex 3da9724e..e1208e2d 100644--- a/web/content/docs/meta.json+++ b/web/content/docs/meta.json@@ -7,6 +7,7 @@"claude-code-plugin","codex-plugin","skills",+ "crawler","self-hosting"]}