Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Check Shopify crawler signatures against the domain when they're saved (#726)
Ben Senescu298912017370
diff --git a/src/client/features/audit/results/ShopifyCrawlWarning.tsx b/src/client/features/audit/results/ShopifyCrawlWarning.tsxindex 45ea74d2..323ba6e4 100644--- a/src/client/features/audit/results/ShopifyCrawlWarning.tsx+++ b/src/client/features/audit/results/ShopifyCrawlWarning.tsx@@ -111,16 +111,17 @@ export function ShopifyCrawlWarning({<AlertDescription className="text-foreground">{signedAndStillLimited ? (<>- Shopify limited this crawl despite your signature. It may have- been created for a different domain than{" "}- <span className="font-mono">{host}</span>. You can replace it in{" "}+ Shopify limited this crawl despite your signature. To check that+ it was created for <span className="font-mono">{host}</span>,+ paste it again in{" "}<Linkto="/p/$projectId/settings/integrations"params={{ projectId }}>Project settings</Link>- .+ . If it was, Shopify is still throttling this store: re-run the+ audit later or with fewer pages.</>) : (<>diff --git a/src/client/features/crawler-access/CrawlerAccessForm.tsx b/src/client/features/crawler-access/CrawlerAccessForm.tsxindex c5102967..e3e7701f 100644--- a/src/client/features/crawler-access/CrawlerAccessForm.tsx+++ b/src/client/features/crawler-access/CrawlerAccessForm.tsx@@ -49,11 +49,12 @@ export function CrawlerAccessForm({saveCrawlerCredential({data: { projectId, ...values },}),- onSuccess: async (saved) => {+ onSuccess: async (result) => {+ if ("problem" in result) return;await queryClient.invalidateQueries({queryKey: crawlerCredentialsQueryKey,});- toast.success(`Crawler access saved for ${saved.host}`);+ toast.success(`Crawler access saved for ${result.credential.host}`);onSaved?.();},});@@ -63,7 +64,21 @@ export function CrawlerAccessForm({validationLogic: revalidateLogic(),validators: { onDynamic: signatureSchema },onSubmit: async ({ value, formApi }) => {- await saveMutation.mutateAsync(value);+ const result = await saveMutation.mutateAsync(value);+ if ("problem" in result) {+ const { problem } = result;+ formApi.setErrorMap({+ onSubmit: {+ fields: {+ signatureInput:+ problem.reason === "wrong_domain"+ ? `This signature was created for ${problem.signedHost}, not ${problem.host}. In Shopify admin, create a signature for ${problem.host}.`+ : `Shopify won't accept this signature for ${problem.host}. Check that you created it for ${problem.host} and copied both values in full.`,+ },+ },+ });+ return;+ }formApi.reset({ ...value, signatureInput: "", signature: "" });},});@@ -100,6 +115,7 @@ export function CrawlerAccessForm({{(field) => (<field.TextFieldlabel="Signature"+ description="Shopify also shows a Signature-Agent value. You don't need to paste it: OpenSEO sends it with every request."type="password"autoComplete="off"data-ph-maskdiff --git a/src/server/features/audit/services/CrawlerCredentialService.test.ts b/src/server/features/audit/services/CrawlerCredentialService.test.tsnew file mode 100644index 00000000..cd0d6e3e--- /dev/null+++ b/src/server/features/audit/services/CrawlerCredentialService.test.ts@@ -0,0 +1,124 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const { upsertMock, listMock } = vi.hoisted(() => ({+ upsertMock: vi.fn(),+ listMock: vi.fn(),+}));++vi.mock("@/server/lib/runtime-env", () => ({+ getOptionalEnvValue: vi+ .fn()+ .mockResolvedValue("test-secret-that-is-at-least-32-chars"),+}));+vi.mock(+ "@/server/features/audit/repositories/CrawlerCredentialRepository",+ () => ({+ CrawlerCredentialRepository: {+ upsert: upsertMock,+ listForOrganization: listMock,+ },+ }),+);++import { CrawlerCredentialService } from "@/server/features/audit/services/CrawlerCredentialService";++// Stands in for the key Shopify publishes in its key directory.+const shopifyKey = await crypto.subtle.generateKey("Ed25519", false, [+ "sign",+ "verify",+]);+const directoryKey = {+ ...(await crypto.subtle.exportKey("jwk", shopifyKey.publicKey)),+ kid: "shopify-key",+};++/** Signs the way Shopify admin does: over the domain and Signature-Agent. */+async function shopifySignature(domain: string) {+ const params = `("@authority" "signature-agent");keyid="shopify-key"`;+ const base = `"@authority": ${domain}\n"signature-agent": "https://shopify.com"\n"@signature-params": ${params}`;+ const signed = await crypto.subtle.sign(+ "Ed25519",+ shopifyKey.privateKey,+ new TextEncoder().encode(base),+ );+ return {+ signatureInput: `sig1=${params}`,+ signature: `sig1=:${Buffer.from(signed).toString("base64")}:`,+ };+}++function save(values: { signatureInput: string; signature: string }) {+ return CrawlerCredentialService.saveCrawlerCredential({+ organizationId: "org-1",+ projectId: "project-1",+ userId: "user-1",+ host: "store.example.com",+ ...values,+ });+}++describe("saveCrawlerCredential", () => {+ beforeEach(() => {+ listMock.mockResolvedValue([+ { projectId: "project-1", host: "store.example.com" },+ ]);+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(Response.json(directoryKey)),+ );+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("saves a signature Shopify made for the domain", async () => {+ const result = await save(await shopifySignature("store.example.com"));++ expect(result).toMatchObject({ credential: { host: "store.example.com" } });+ });++ it("names the domain a www-twin signature was made for", async () => {+ const result = await save(await shopifySignature("www.store.example.com"));++ expect(result).toEqual({+ problem: {+ reason: "wrong_domain",+ host: "store.example.com",+ signedHost: "www.store.example.com",+ },+ });+ expect(upsertMock).not.toHaveBeenCalled();+ });++ it.each([+ [+ "the Signature pasted into both fields",+ async () => {+ const { signature } = await shopifySignature("store.example.com");+ return { signatureInput: signature, signature };+ },+ ],+ [+ "a signature for another store",+ () => shopifySignature("other-store.example.com"),+ ],+ ])("rejects %s", async (_case, values) => {+ const result = await save(await values());++ expect(result).toEqual({+ problem: { reason: "invalid", host: "store.example.com" },+ });+ expect(upsertMock).not.toHaveBeenCalled();+ });++ it("saves unchecked when Shopify's key directory is unreachable", async () => {+ vi.mocked(fetch).mockRejectedValue(new TypeError("fetch failed"));++ const result = await save(+ await shopifySignature("other-store.example.com"),+ );++ expect(result).toMatchObject({ credential: { host: "store.example.com" } });+ });+});diff --git a/src/server/features/audit/services/CrawlerCredentialService.ts b/src/server/features/audit/services/CrawlerCredentialService.tsindex ac296228..490fdebd 100644--- a/src/server/features/audit/services/CrawlerCredentialService.ts+++ b/src/server/features/audit/services/CrawlerCredentialService.ts@@ -1,5 +1,9 @@import { symmetricDecrypt, symmetricEncrypt } from "better-auth/crypto";import { CrawlerCredentialRepository } from "@/server/features/audit/repositories/CrawlerCredentialRepository";+import {+ checkShopifySignature,+ type ShopifySignatureProblem,+} from "@/server/features/audit/services/shopifySignature";import { AppError } from "@/server/lib/errors";import { getOptionalEnvValue } from "@/server/lib/runtime-env";import {@@ -72,6 +76,10 @@ async function listCrawlerCredentials(return rows.map(toSummary);}+/**+ * A signature Shopify would ignore on this host comes back as a problem to+ * show next to the form, instead of being stored and failing as 429s.+ */async function saveCrawlerCredential(input: {organizationId: string;projectId: string;@@ -79,8 +87,18 @@ async function saveCrawlerCredential(input: {host: string;signatureInput: string;signature: string;-}): Promise<CrawlerCredentialSummary> {+}): Promise<+ | { credential: CrawlerCredentialSummary }+ | { problem: ShopifySignatureProblem }+> {const key = await getEncryptionKey();+ const problem = await checkShopifySignature({+ host: input.host,+ signatureInput: input.signatureInput,+ signature: input.signature,+ });+ if (problem) return { problem };+await CrawlerCredentialRepository.upsert({id: crypto.randomUUID(),projectId: input.projectId,@@ -96,7 +114,7 @@ async function saveCrawlerCredential(input: {await CrawlerCredentialRepository.listForOrganization(input.organizationId)).find((row) => row.projectId === input.projectId && row.host === input.host);if (!saved) throw new AppError("INTERNAL_ERROR");- return toSummary(saved);+ return { credential: toSummary(saved) };}async function deleteCrawlerCredential(input: {diff --git a/src/server/features/audit/services/shopifySignature.ts b/src/server/features/audit/services/shopifySignature.tsnew file mode 100644index 00000000..82d1c1e1--- /dev/null+++ b/src/server/features/audit/services/shopifySignature.ts@@ -0,0 +1,96 @@+import { z } from "zod";+import { SHOPIFY_SIGNATURE_AGENT } from "@/shared/crawler-access";++/**+ * Checks a Shopify crawler-access signature against the domain it will be+ * sent to, before it is saved.+ *+ * Shopify signs two things with the key it publishes: the domain picked in+ * Shopify admin (`@authority`) and the `Signature-Agent` value. Shopify+ * ignores a signature made for another domain (`www.` versus the bare domain+ * is the usual slip) or pasted incompletely, and rate-limits the crawl as if+ * it were unsigned. Checking here tells the merchant why at save time.+ */++const SHOPIFY_KEY_DIRECTORY_URL =+ "https://shopify.com/.well-known/http-message-signatures-directory";++export type ShopifySignatureProblem =+ | { reason: "wrong_domain"; host: string; signedHost: string }+ | { reason: "invalid"; host: string };++const directoryKeySchema = z.object({ kid: z.string(), x: z.string() });++/**+ * Null means the signature is fine for `host`, or couldn't be checked: an+ * unreachable key directory must not block a save.+ */+export async function checkShopifySignature(input: {+ host: string;+ signatureInput: string;+ signature: string;+}): Promise<ShopifySignatureProblem | null> {+ const { host, signatureInput } = input;+ const params = /^\w+=(\(.+)$/.exec(signatureInput)?.[1];+ const keyId = /;keyid="([^"]+)"/.exec(signatureInput)?.[1];+ const signatureBytes = decodeSignature(input.signature);+ if (!params || !keyId || !signatureBytes) return { reason: "invalid", host };++ const key = await importShopifyKey(keyId);+ if (!key) return null;++ // RFC 9421 signature base over what Shopify signs, ending with the+ // signature parameters exactly as they appear after the label.+ const verifiesFor = (domain: string) =>+ crypto.subtle.verify(+ "Ed25519",+ key,+ signatureBytes,+ new TextEncoder().encode(+ `"@authority": ${domain}\n"signature-agent": ${SHOPIFY_SIGNATURE_AGENT}\n"@signature-params": ${params}`,+ ),+ );++ if (await verifiesFor(host)) return null;+ const twinHost = host.startsWith("www.") ? host.slice(4) : `www.${host}`;+ if (await verifiesFor(twinHost)) {+ return { reason: "wrong_domain", host, signedHost: twinHost };+ }+ return { reason: "invalid", host };+}++/** The bytes of a `sig1=:<base64>:` value, or null if it isn't one. */+function decodeSignature(signature: string): Uint8Array<ArrayBuffer> | null {+ const base64 = /^\w+=:([A-Za-z0-9+/]+={0,2}):$/.exec(signature)?.[1];+ if (!base64) return null;+ try {+ const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));+ // Ed25519 signatures are 64 bytes, and the Workers runtime throws on any+ // other length instead of failing the verify.+ return bytes.length === 64 ? bytes : null;+ } catch {+ return null;+ }+}++async function importShopifyKey(keyId: string): Promise<CryptoKey | null> {+ try {+ const response = await fetch(SHOPIFY_KEY_DIRECTORY_URL, {+ signal: AbortSignal.timeout(5_000),+ });+ const { kid, x } = directoryKeySchema.parse(await response.json());+ // A signature made with a key Shopify has since rotated out may still be+ // valid, so it is left unchecked rather than rejected.+ if (kid !== keyId) return null;+ return await crypto.subtle.importKey(+ "jwk",+ { kty: "OKP", crv: "Ed25519", x },+ "Ed25519",+ false,+ ["verify"],+ );+ } catch (error) {+ console.warn("Skipped the Shopify signature check:", error);+ return null;+ }+}diff --git a/src/shared/crawler-access.ts b/src/shared/crawler-access.tsindex bb04659a..d3c8e1c0 100644--- a/src/shared/crawler-access.ts+++ b/src/shared/crawler-access.ts@@ -11,7 +11,7 @@*//** Constant Shopify expects, quotes included. We supply it; users never see it. */-const SHOPIFY_SIGNATURE_AGENT = '"https://shopify.com"';+export const SHOPIFY_SIGNATURE_AGENT = '"https://shopify.com"';export const SHOPIFY_CRAWLER_ACCESS_DOC_URL ="https://help.shopify.com/en/manual/promoting-marketing/seo/crawling-your-store";diff --git a/web/content/docs/skills/seo-audit.mdx b/web/content/docs/skills/seo-audit.mdxindex 37906ceb..003b18a9 100644--- a/web/content/docs/skills/seo-audit.mdx+++ b/web/content/docs/skills/seo-audit.mdx@@ -53,16 +53,20 @@ If you own the store, you can authorize OpenSEO in about a minute:click **Create signature**.2. Pick the domain you audit (for example `www.your-store.com`) and an expiryof up to three months.-3. Copy the `Signature-Input` and `Signature` values.+3. Copy the `Signature-Input` and `Signature` values. Shopify also shows a+ `Signature-Agent` value; you don't need it, because OpenSEO sends it for you.A signature works only for the exact domain you picked, so `www.your-store.com`and `your-store.com` each need their own.Paste both values into OpenSEO, either on the warning shown at the top of the-audit report or under **Project settings → Integrations → Crawler access**. Every audit-request to that domain then carries the signature, and you can re-run the audit-right away. The signature is saved on that website's project, and any other-project in your organization that audits the same domain uses it too.+audit report or under **Project settings → Integrations → Crawler access**.+OpenSEO checks the signature against Shopify's published key when you save it.+If it was made for a different domain, or a value was cut off when you copied+it, OpenSEO tells you instead of saving it. Every audit request to that domain+then carries the signature, and you can re-run the audit right away. The+signature is saved on that website's project, and any other project in your+organization that audits the same domain uses it too.Shopify signatures last at most three months and cannot be renewed. OpenSEOstops sending a signature once it expires, and the audit report tells you when