Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Verify Shopify store ownership before saving shopifyStoreId

Kiran K628dbb46557b
diff --git a/apps/web/app/(ee)/api/shopify/integration/callback/route.ts b/apps/web/app/(ee)/api/shopify/integration/callback/route.ts
index d18fad23aa..2ee910f80f 100644
--- a/apps/web/app/(ee)/api/shopify/integration/callback/route.ts
+++ b/apps/web/app/(ee)/api/shopify/integration/callback/route.ts
@@ -3,6 +3,8 @@ import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { encrypt } from "@/lib/encryption";
import { installIntegration } from "@/lib/integrations/install";
+import { isValidShopifyStoreId } from "@/lib/integrations/shopify/store-id";
+import { verifyShopifyStoreOwnership } from "@/lib/integrations/shopify/verify-store-ownership";
import { prisma } from "@/lib/prisma";
import { SHOPIFY_INTEGRATION_ID } from "@dub/utils";
import { NextResponse } from "next/server";
@@ -11,7 +13,13 @@ import * as z from "zod/v4";
const requestSchema = z.discriminatedUnion("action", [
z.object({
action: z.literal("connect"),
- shopifyStoreId: z.string().min(1),
+ shopifyStoreId: z
+ .string()
+ .trim()
+ .toLowerCase()
+ .refine(isValidShopifyStoreId, {
+ message: "Invalid Shopify store domain.",
+ }),
accessToken: z.string().min(1),
scope: z.string().min(1),
}),
@@ -27,6 +35,13 @@ export const PATCH = withWorkspace(
async ({ req, workspace, session }) => {
const body = requestSchema.parse(await parseRequestBody(req));
+ if (body.action === "connect") {
+ await verifyShopifyStoreOwnership({
+ shopifyStoreId: body.shopifyStoreId,
+ accessToken: body.accessToken,
+ });
+ }
+
try {
const response = await prisma.project.update({
where: {
diff --git a/apps/web/lib/integrations/shopify/admin-graphql.ts b/apps/web/lib/integrations/shopify/admin-graphql.ts
index c3bf1bbf88..f5a694ed2f 100644
--- a/apps/web/lib/integrations/shopify/admin-graphql.ts
+++ b/apps/web/lib/integrations/shopify/admin-graphql.ts
@@ -1,3 +1,5 @@
+import { isValidShopifyStoreId } from "./store-id";
+
const SHOPIFY_ADMIN_API_VERSION = "2025-04";
export class ShopifyAdminGraphqlError extends Error {
@@ -24,6 +26,13 @@ export async function shopifyAdminGraphql<T>({
query: string;
variables?: Record<string, unknown>;
}): Promise<T> {
+ if (!isValidShopifyStoreId(shopifyStoreId)) {
+ throw new ShopifyAdminGraphqlError(
+ "invalid_store",
+ "Invalid Shopify store domain.",
+ );
+ }
+
const response = await fetch(
`https://${shopifyStoreId}/admin/api/${SHOPIFY_ADMIN_API_VERSION}/graphql.json`,
{
diff --git a/apps/web/lib/integrations/shopify/store-id.ts b/apps/web/lib/integrations/shopify/store-id.ts
new file mode 100644
index 0000000000..dcd2eee5eb
--- /dev/null
+++ b/apps/web/lib/integrations/shopify/store-id.ts
@@ -0,0 +1,7 @@
+const SHOPIFY_STORE_ID_REGEX = /^[a-z0-9][a-z0-9-]*\.myshopify\.com$/;
+
+// Rejects store IDs that are not a `*.myshopify.com` domain. The store ID is
+// used as the Admin API hostname, so anything else could redirect the request.
+export function isValidShopifyStoreId(storeId: string): boolean {
+ return typeof storeId === "string" && SHOPIFY_STORE_ID_REGEX.test(storeId);
+}
diff --git a/apps/web/lib/integrations/shopify/verify-store-ownership.ts b/apps/web/lib/integrations/shopify/verify-store-ownership.ts
new file mode 100644
index 0000000000..a390cbf771
--- /dev/null
+++ b/apps/web/lib/integrations/shopify/verify-store-ownership.ts
@@ -0,0 +1,41 @@
+import { DubApiError } from "@/lib/api/errors";
+import { shopifyAdminGraphql } from "./admin-graphql";
+
+// Webhooks are routed by `shopifyStoreId`, so the access token must belong to
+// the store before a workspace is allowed to claim it.
+export async function verifyShopifyStoreOwnership({
+ shopifyStoreId,
+ accessToken,
+}: {
+ shopifyStoreId: string;
+ accessToken: string;
+}) {
+ let myshopifyDomain: string | undefined;
+
+ try {
+ const data = await shopifyAdminGraphql<{
+ shop?: { myshopifyDomain?: string };
+ }>({
+ shopifyStoreId,
+ accessToken,
+ query: /* GraphQL */ `
+ query {
+ shop {
+ myshopifyDomain
+ }
+ }
+ `,
+ });
+
+ myshopifyDomain = data?.shop?.myshopifyDomain;
+ } catch {
+ myshopifyDomain = undefined;
+ }
+
+ if (myshopifyDomain?.toLowerCase() !== shopifyStoreId) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Could not verify access to this Shopify store.",
+ });
+ }
+}
diff --git a/apps/web/tests/misc/shopify-integration-callback.test.ts b/apps/web/tests/misc/shopify-integration-callback.test.ts
new file mode 100644
index 0000000000..9e3c933504
--- /dev/null
+++ b/apps/web/tests/misc/shopify-integration-callback.test.ts
@@ -0,0 +1,163 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { PATCH } from "../../app/(ee)/api/shopify/integration/callback/route";
+import { shopifyAdminGraphql } from "../../lib/integrations/shopify/admin-graphql";
+
+const mocks = vi.hoisted(() => ({
+ updateProject: vi.fn(),
+ deleteInstalledIntegration: vi.fn(),
+ installIntegration: vi.fn(),
+}));
+
+vi.mock("@/lib/auth", () => ({
+ withWorkspace: (handler: unknown) => handler,
+}));
+vi.mock("@/lib/api/utils", () => ({
+ parseRequestBody: (req: Request) => req.json(),
+}));
+vi.mock("@/lib/api/errors", () => ({
+ DubApiError: class extends Error {
+ code: string;
+ constructor({ code, message }: { code: string; message: string }) {
+ super(message);
+ this.code = code;
+ }
+ },
+}));
+vi.mock("@/lib/encryption", () => ({
+ encrypt: (value: string) => `encrypted:${value}`,
+}));
+vi.mock("@/lib/integrations/install", () => ({
+ installIntegration: mocks.installIntegration,
+}));
+vi.mock("@/lib/prisma", () => ({
+ prisma: {
+ project: { update: mocks.updateProject },
+ installedIntegration: { delete: mocks.deleteInstalledIntegration },
+ },
+}));
+
+// The middleware mock exposes the wrapped callback.
+const callback = PATCH as unknown as (ctx: {
+ req: Request;
+ workspace: { id: string };
+ session: { user: { id: string } };
+}) => Promise<Response>;
+
+const patch = (body: Record<string, unknown>) =>
+ callback({
+ req: new Request("http://localhost/api/shopify/integration/callback", {
+ method: "PATCH",
+ body: JSON.stringify(body),
+ }),
+ workspace: { id: "ws_1" },
+ session: { user: { id: "user_1" } },
+ });
+
+const connect = (shopifyStoreId: string) =>
+ patch({
+ action: "connect",
+ shopifyStoreId,
+ accessToken: "shpat_test",
+ scope: "read_orders,write_discounts",
+ });
+
+const shopifyReturns = (response: Response) =>
+ vi.mocked(fetch).mockResolvedValue(response);
+
+describe("PATCH /api/shopify/integration/callback", () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ vi.stubGlobal("fetch", vi.fn());
+ mocks.updateProject.mockImplementation(async ({ data }) => data);
+ });
+
+ it.each(["evil.com/x?", "169.254.169.254", "acme.myshopify.com.evil.com"])(
+ "rejects %s without contacting it or saving it",
+ async (shopifyStoreId) => {
+ await expect(connect(shopifyStoreId)).rejects.toThrow();
+
+ expect(fetch).not.toHaveBeenCalled();
+ expect(mocks.updateProject).not.toHaveBeenCalled();
+ },
+ );
+
+ it("rejects a token Shopify does not accept for the store", async () => {
+ shopifyReturns(new Response("Unauthorized", { status: 401 }));
+
+ await expect(connect("acme.myshopify.com")).rejects.toMatchObject({
+ code: "forbidden",
+ });
+ expect(mocks.updateProject).not.toHaveBeenCalled();
+ });
+
+ it("rejects a token that belongs to a different store", async () => {
+ shopifyReturns(
+ Response.json({
+ data: { shop: { myshopifyDomain: "attacker.myshopify.com" } },
+ }),
+ );
+
+ await expect(connect("acme.myshopify.com")).rejects.toMatchObject({
+ code: "forbidden",
+ });
+ expect(mocks.updateProject).not.toHaveBeenCalled();
+ });
+
+ it("saves the store when the token belongs to it", async () => {
+ shopifyReturns(
+ Response.json({
+ data: { shop: { myshopifyDomain: "acme.myshopify.com" } },
+ }),
+ );
+
+ const res = await connect(" Acme.myshopify.com ");
+
+ expect(res.status).toBe(200);
+ expect(String(vi.mocked(fetch).mock.calls[0][0])).toMatch(
+ /^https:\/\/acme\.myshopify\.com\/admin\/api\//,
+ );
+ expect(mocks.updateProject).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: { shopifyStoreId: "acme.myshopify.com" },
+ }),
+ );
+ expect(mocks.installIntegration).toHaveBeenCalledWith(
+ expect.objectContaining({
+ workspaceId: "ws_1",
+ credentials: {
+ accessToken: "encrypted:shpat_test",
+ scope: "read_orders,write_discounts",
+ },
+ }),
+ );
+ });
+
+ it("disconnects without contacting Shopify", async () => {
+ const res = await patch({ action: "disconnect", shopifyStoreId: null });
+
+ expect(res.status).toBe(200);
+ expect(fetch).not.toHaveBeenCalled();
+ expect(mocks.updateProject).toHaveBeenCalledWith(
+ expect.objectContaining({ data: { shopifyStoreId: null } }),
+ );
+ expect(mocks.deleteInstalledIntegration).toHaveBeenCalled();
+ });
+});
+
+describe("shopifyAdminGraphql", () => {
+ beforeEach(() => {
+ vi.stubGlobal("fetch", vi.fn());
+ });
+
+ it("does not send requests for an invalid stored store ID", async () => {
+ await expect(
+ shopifyAdminGraphql({
+ shopifyStoreId: "evil.com/x?",
+ accessToken: "shpat_test",
+ query: "query { shop { id } }",
+ }),
+ ).rejects.toMatchObject({ code: "invalid_store" });
+
+ expect(fetch).not.toHaveBeenCalled();
+ });
+});