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.

Migrate domains API tests to Playwright and reject invalid JSON configs

Kiran K5c4795e9bde2
diff --git a/apps/web/app/api/domains/[domain]/route.ts b/apps/web/app/api/domains/[domain]/route.ts
index 0c2fbce497..434e0d4bbb 100644
--- a/apps/web/app/api/domains/[domain]/route.ts
+++ b/apps/web/app/api/domains/[domain]/route.ts
@@ -12,7 +12,10 @@ import { withWorkspace } from "@/lib/auth";
import { setRenewOption } from "@/lib/dynadot/set-renew-option";
import { prisma } from "@/lib/prisma";
import { storage } from "@/lib/storage";
-import { updateDomainBodySchema } from "@/lib/zod/schemas/domains";
+import {
+ domainJsonConfigSchema,
+ updateDomainBodySchema,
+} from "@/lib/zod/schemas/domains";
import { combineWords, nanoid, R2_URL } from "@dub/utils";
import { Prisma } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
@@ -21,7 +24,7 @@ import { NextResponse } from "next/server";
import * as z from "zod/v4";
const updateDomainBodySchemaExtended = updateDomainBodySchema.extend({
- deepviewData: z.string().nullish(),
+ deepviewData: domainJsonConfigSchema,
autoRenew: z.boolean().nullish(),
});
diff --git a/apps/web/lib/zod/schemas/domains.ts b/apps/web/lib/zod/schemas/domains.ts
index 719eb28c05..907cb56b0c 100644
--- a/apps/web/lib/zod/schemas/domains.ts
+++ b/apps/web/lib/zod/schemas/domains.ts
@@ -103,6 +103,27 @@ export const getDefaultDomainsQuerySchema = getDomainsQuerySchema.pick({
search: true,
});
+export const domainJsonConfigSchema = z
+ .string()
+ .nullish()
+ .refine(
+ (val) => {
+ if (val == null || val === "") {
+ return true;
+ }
+
+ try {
+ JSON.parse(val);
+ return true;
+ } catch {
+ return false;
+ }
+ },
+ {
+ error: "Invalid JSON",
+ },
+ );
+
export const createDomainBodySchema = z.object({
slug: z
.string({ error: "slug is required" })
@@ -141,22 +162,16 @@ export const createDomainBodySchema = z.object({
)
.meta({ example: "https://dub.co/help/article/dub-links" }),
logo: uploadedImageSchema.nullish().describe("The logo of the domain."),
- assetLinks: z
- .string()
- .nullish()
- .describe(
- "assetLinks.json configuration file (for deep link support on Android).",
- ),
- appleAppSiteAssociation: z
- .string()
- .nullish()
- .describe(
- "apple-app-site-association configuration file (for deep link support on iOS).",
- ),
+ assetLinks: domainJsonConfigSchema.describe(
+ "assetLinks.json configuration file (for deep link support on Android).",
+ ),
+ appleAppSiteAssociation: domainJsonConfigSchema.describe(
+ "apple-app-site-association configuration file (for deep link support on iOS).",
+ ),
});
export const createDomainBodySchemaExtended = createDomainBodySchema.extend({
- deepviewData: z.string().nullish(),
+ deepviewData: domainJsonConfigSchema,
isOnboardingSubdomainFlow: z.boolean().default(false),
});
diff --git a/apps/web/playwright/api/domains/domains.spec.ts b/apps/web/playwright/api/domains/domains.spec.ts
new file mode 100644
index 0000000000..d449703535
--- /dev/null
+++ b/apps/web/playwright/api/domains/domains.spec.ts
@@ -0,0 +1,572 @@
+import type { DomainProps } from "@/lib/types";
+import { expect } from "@playwright/test";
+import { randomName } from "../../utils";
+import { test, type ApiClient } from "../fixtures";
+
+test.describe.configure({
+ mode: "serial",
+});
+
+const VALID_ASSET_LINKS = JSON.stringify([
+ {
+ relation: ["delegate_permission/common.handle_all_urls"],
+ target: {
+ namespace: "android_app",
+ package_name: "com.example.app",
+ sha256_cert_fingerprints: ["AA:BB:CC"],
+ },
+ },
+]);
+
+const VALID_AASA = JSON.stringify({
+ applinks: {
+ apps: [],
+ details: [{ appID: "TEAMID.com.example.app", paths: ["*"] }],
+ },
+});
+
+const VALID_DEEPVIEW = JSON.stringify({
+ title: "Welcome",
+ description: "Hi",
+});
+
+const UPDATED_ASSET_LINKS = JSON.stringify([
+ {
+ relation: ["delegate_permission/common.handle_all_urls"],
+ target: {
+ namespace: "android_app",
+ package_name: "com.example.app.updated",
+ sha256_cert_fingerprints: ["DD:EE:FF"],
+ },
+ },
+]);
+
+const UPDATED_AASA = JSON.stringify({
+ applinks: {
+ apps: [],
+ details: [{ appID: "TEAMID.com.example.updated", paths: ["/app/*"] }],
+ },
+});
+
+const UPDATED_DEEPVIEW = JSON.stringify({
+ title: "Updated",
+ description: "New copy",
+});
+
+const INVALID_JSON = "not-json";
+
+type JsonConfigFields = {
+ assetLinks?: string | null;
+ appleAppSiteAssociation?: string | null;
+ deepviewData?: string | null;
+};
+
+type DomainCreateBody = ReturnType<typeof domainBody> & JsonConfigFields;
+
+const jsonFields = [
+ {
+ field: "assetLinks" as const,
+ valid: VALID_ASSET_LINKS,
+ updated: UPDATED_ASSET_LINKS,
+ emptyCreateExpected: null,
+ },
+ {
+ field: "appleAppSiteAssociation" as const,
+ valid: VALID_AASA,
+ updated: UPDATED_AASA,
+ emptyCreateExpected: null,
+ },
+ {
+ field: "deepviewData" as const,
+ valid: VALID_DEEPVIEW,
+ updated: UPDATED_DEEPVIEW,
+ emptyCreateExpected: "{}",
+ },
+];
+
+function randomDomainSlug() {
+ return `${randomName("domain").toLowerCase()}.dub-internal-test.com`;
+}
+
+function domainBody(slug: string) {
+ return {
+ slug,
+ expiredUrl: `https://${slug}/expired`,
+ placeholder: `https://${slug}/placeholder`,
+ notFoundUrl: `https://${slug}/not-found`,
+ };
+}
+
+function expectedDomain(body: DomainCreateBody) {
+ return {
+ id: expect.any(String),
+ slug: body.slug,
+ verified: expect.any(Boolean),
+ primary: expect.any(Boolean),
+ archived: false,
+ placeholder: body.placeholder,
+ expiredUrl: body.expiredUrl,
+ notFoundUrl: body.notFoundUrl,
+ createdAt: expect.any(String),
+ updatedAt: expect.any(String),
+ registeredDomain: null,
+ logo: null,
+ appleAppSiteAssociation: body.appleAppSiteAssociation
+ ? JSON.parse(body.appleAppSiteAssociation)
+ : null,
+ assetLinks: body.assetLinks ? JSON.parse(body.assetLinks) : null,
+ deepviewData: body.deepviewData ? JSON.parse(body.deepviewData) : {},
+ };
+}
+
+function domainJsonForCompare(domain: DomainProps) {
+ return {
+ ...domain,
+ assetLinks: domain.assetLinks ? JSON.parse(domain.assetLinks) : null,
+ appleAppSiteAssociation: domain.appleAppSiteAssociation
+ ? JSON.parse(domain.appleAppSiteAssociation)
+ : null,
+ deepviewData: domain.deepviewData ? JSON.parse(domain.deepviewData) : null,
+ };
+}
+
+function expectDomainEqual(actual: DomainProps, expected: DomainCreateBody) {
+ expect(domainJsonForCompare(actual)).toStrictEqual(expectedDomain(expected));
+}
+
+function expectJsonFieldEqual(
+ actual: string | null | undefined,
+ expected: string | null,
+) {
+ if (expected === null) {
+ expect(actual ?? null).toBeNull();
+ return;
+ }
+
+ expect(actual).toEqual(expect.any(String));
+ expect(JSON.parse(actual!)).toEqual(JSON.parse(expected));
+}
+
+async function createDomain(
+ api: ApiClient,
+ overrides: Partial<DomainCreateBody> = {},
+) {
+ const slug = overrides.slug ?? randomDomainSlug();
+ const body = { ...domainBody(slug), ...overrides };
+ const response = await api.post<DomainProps>("/api/domains", body);
+
+ expect(response.status).toEqual(201);
+ return { ...response, body };
+}
+
+async function deleteDomain(api: ApiClient, slug: string | undefined) {
+ if (!slug) return;
+ await api.delete(`/api/domains/${slug}`);
+}
+
+test("POST /domains", async ({ api }) => {
+ let slug: string | undefined;
+
+ try {
+ const { status, data, body } = await createDomain(api);
+ slug = data.slug;
+
+ expect(status).toEqual(201);
+ expectDomainEqual(data, body);
+ } finally {
+ await deleteDomain(api, slug);
+ }
+});
+
+test("GET /domains/{slug}", async ({ api }) => {
+ let slug: string | undefined;
+
+ try {
+ const { data: created } = await createDomain(api);
+ slug = created.slug;
+
+ const { status, data } = await api.get<DomainProps>(`/api/domains/${slug}`);
+
+ expect(status).toEqual(200);
+ expect(data).toStrictEqual(created);
+ } finally {
+ await deleteDomain(api, slug);
+ }
+});
+
+test("GET /domains", async ({ api }) => {
+ let slug: string | undefined;
+
+ try {
+ const { data: created } = await createDomain(api);
+ slug = created.slug;
+
+ const { status, data } = await api.get<DomainProps[]>("/api/domains");
+
+ expect(status).toEqual(200);
+ expect(data).toEqual(expect.arrayContaining([created]));
+ } finally {
+ await deleteDomain(api, slug);
+ }
+});
+
+test("POST /domains/{slug}/primary", async ({ api }) => {
+ let slug: string | undefined;
+
+ try {
+ const { data: created } = await createDomain(api);
+ slug = created.slug;
+
+ const { status, data } = await api.post<DomainProps>(
+ `/api/domains/${slug}/primary`,
+ );
+
+ expect(status).toEqual(200);
+ expect(data).toStrictEqual({
+ ...created,
+ primary: true,
+ updatedAt: expect.any(String),
+ });
+ } finally {
+ await deleteDomain(api, slug);
+ }
+});
+
+test("PATCH /domains/{slug}", async ({ api }) => {
+ let slug: string | undefined;
+
+ try {
+ const { data: created } = await createDomain(api);
+ slug = created.slug;
+
+ const toUpdate = {
+ expiredUrl: `https://${slug}/expired-new`,
+ placeholder: `https://${slug}/placeholder-new`,
+ notFoundUrl: `https://${slug}/not-found-new`,
+ archived: true,
+ };
+
+ const { status, data } = await api.patch<DomainProps>(
+ `/api/domains/${slug}`,
+ toUpdate,
+ );
+
+ expect(status).toEqual(200);
+ expect(data).toStrictEqual({
+ ...created,
+ ...toUpdate,
+ updatedAt: expect.any(String),
+ });
+ } finally {
+ await deleteDomain(api, slug);
+ }
+});
+
+test("DELETE /domains/{slug}", async ({ api }) => {
+ const { data: created } = await createDomain(api);
+
+ const { status, data } = await api.delete<{ slug: string }>(
+ `/api/domains/${created.slug}`,
+ );
+
+ expect(status).toEqual(200);
+ expect(data).toStrictEqual({ slug: created.slug });
+
+ const { status: listStatus, data: domains } =
+ await api.get<DomainProps[]>("/api/domains");
+
+ expect(listStatus).toEqual(200);
+ expect(domains.find((d) => d.slug === created.slug)).toBeUndefined();
+});
+
+test("GET /domains/status – not eligible", async ({ api }) => {
+ const { status, data } = await api.get(
+ "/api/domains/status?domains=example.link",
+ );
+
+ expect(status).toEqual(403);
+ expect(data).toEqual({
+ error: {
+ code: "forbidden",
+ message:
+ "GET /domains/status is not available for your workspace. Contact support for more information.",
+ doc_url: "https://dub.co/docs/api-reference/errors#forbidden",
+ },
+ });
+});
+
+const errorCases = [
+ {
+ name: "POST /domains – without slug",
+ body: {},
+ expected: {
+ status: 422,
+ data: {
+ error: {
+ code: "unprocessable_entity",
+ message: "invalid_type: slug: slug is required",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ },
+ },
+ },
+ {
+ name: "POST /domains – invalid domain",
+ body: { slug: "not a domain" },
+ expected: {
+ status: 422,
+ data: {
+ error: {
+ code: "unprocessable_entity",
+ message: "Invalid domain",
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ },
+ },
+ },
+];
+
+for (const { name, body, expected } of errorCases) {
+ test(name, async ({ api }) => {
+ expect(await api.post("/api/domains", body)).toEqual(expected);
+ });
+}
+
+test("POST /domains – existing slug", async ({ api }) => {
+ let slug: string | undefined;
+
+ try {
+ const { data: created } = await createDomain(api);
+ slug = created.slug;
+
+ const { status, data } = await api.post("/api/domains", {
+ slug,
+ });
+
+ expect(status).toEqual(409);
+ expect(data).toEqual({
+ error: {
+ code: "conflict",
+ message: "Domain is already in use.",
+ doc_url: "https://dub.co/docs/api-reference/errors#conflict",
+ },
+ });
+ } finally {
+ await deleteDomain(api, slug);
+ }
+});
+
+test("GET /domains/{slug} – not found", async ({ api }) => {
+ const slug = randomDomainSlug();
+
+ const { status, data } = await api.get(`/api/domains/${slug}`);
+
+ expect(status).toEqual(404);
+ expect(data).toEqual({
+ error: {
+ code: "not_found",
+ message: `Domain ${slug} not found.`,
+ doc_url: "https://dub.co/docs/api-reference/errors#not-found",
+ },
+ });
+});
+
+test.describe("JSON config fields", () => {
+ for (const { field, valid, updated, emptyCreateExpected } of jsonFields) {
+ test(`POST /domains – valid ${field}`, async ({ api }) => {
+ let slug: string | undefined;
+
+ try {
+ const { status, data, body } = await createDomain(api, {
+ [field]: valid,
+ });
+ slug = data.slug;
+
+ expect(status).toEqual(201);
+ expectDomainEqual(data, body);
+ expectJsonFieldEqual(data[field], valid);
+ } finally {
+ await deleteDomain(api, slug);
+ }
+ });
+
+ test(`PATCH /domains/{slug} – update ${field}`, async ({ api }) => {
+ let slug: string | undefined;
+
+ try {
+ const { data: created } = await createDomain(api);
+ slug = created.slug;
+
+ const { status, data } = await api.patch<DomainProps>(
+ `/api/domains/${slug}`,
+ { [field]: updated },
+ );
+
+ expect(status).toEqual(200);
+ expectJsonFieldEqual(data[field], updated);
+ } finally {
+ await deleteDomain(api, slug);
+ }
+ });
+
+ test(`POST /domains – empty ${field}`, async ({ api }) => {
+ let slug: string | undefined;
+
+ try {
+ const { status, data } = await createDomain(api, {
+ [field]: "",
+ });
+ slug = data.slug;
+
+ expect(status).toEqual(201);
+ expect(data[field]).toEqual(emptyCreateExpected);
+ } finally {
+ await deleteDomain(api, slug);
+ }
+ });
+
+ test(`PATCH /domains/{slug} – clear ${field} with null`, async ({
+ api,
+ }) => {
+ let slug: string | undefined;
+
+ try {
+ const { data: created } = await createDomain(api, {
+ [field]: valid,
+ });
+ slug = created.slug;
+
+ const { status, data } = await api.patch<DomainProps>(
+ `/api/domains/${slug}`,
+ { [field]: null },
+ );
+
+ expect(status).toEqual(200);
+ expect(data[field]).toBeNull();
+ } finally {
+ await deleteDomain(api, slug);
+ }
+ });
+
+ test(`PATCH /domains/{slug} – clear ${field} with empty string`, async ({
+ api,
+ }) => {
+ let slug: string | undefined;
+
+ try {
+ const { data: created } = await createDomain(api, {
+ [field]: valid,
+ });
+ slug = created.slug;
+
+ const { status, data } = await api.patch<DomainProps>(
+ `/api/domains/${slug}`,
+ { [field]: "" },
+ );
+
+ expect(status).toEqual(200);
+ expect(data[field]).toBeNull();
+ } finally {
+ await deleteDomain(api, slug);
+ }
+ });
+
+ test(`POST /domains – invalid ${field} JSON`, async ({ api }) => {
+ const slug = randomDomainSlug();
+
+ expect(
+ await api.post("/api/domains", {
+ ...domainBody(slug),
+ [field]: INVALID_JSON,
+ }),
+ ).toEqual({
+ status: 422,
+ data: {
+ error: {
+ code: "unprocessable_entity",
+ message: `custom: ${field}: Invalid JSON`,
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ },
+ });
+ });
+
+ test(`PATCH /domains/{slug} – invalid ${field} JSON`, async ({ api }) => {
+ let slug: string | undefined;
+
+ try {
+ const { data: created } = await createDomain(api);
+ slug = created.slug;
+
+ expect(
+ await api.patch(`/api/domains/${slug}`, {
+ [field]: INVALID_JSON,
+ }),
+ ).toEqual({
+ status: 422,
+ data: {
+ error: {
+ code: "unprocessable_entity",
+ message: `custom: ${field}: Invalid JSON`,
+ doc_url:
+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",
+ },
+ },
+ });
+ } finally {
+ await deleteDomain(api, slug);
+ }
+ });
+ }
+
+ test("POST + PATCH – create, update, and clear all JSON fields", async ({
+ api,
+ }) => {
+ let slug: string | undefined;
+
+ try {
+ const { data: created, body } = await createDomain(api, {
+ assetLinks: VALID_ASSET_LINKS,
+ appleAppSiteAssociation: VALID_AASA,
+ deepviewData: VALID_DEEPVIEW,
+ });
+ slug = created.slug;
+
+ expect(created).toEqual(expect.objectContaining({ slug: body.slug }));
+ expectDomainEqual(created, body);
+
+ const updatedPayload = {
+ assetLinks: UPDATED_ASSET_LINKS,
+ appleAppSiteAssociation: UPDATED_AASA,
+ deepviewData: UPDATED_DEEPVIEW,
+ };
+
+ const { status: updateStatus, data: updated } =
+ await api.patch<DomainProps>(`/api/domains/${slug}`, updatedPayload);
+
+ expect(updateStatus).toEqual(200);
+ expectJsonFieldEqual(updated.assetLinks, UPDATED_ASSET_LINKS);
+ expectJsonFieldEqual(updated.appleAppSiteAssociation, UPDATED_AASA);
+ expectJsonFieldEqual(updated.deepviewData, UPDATED_DEEPVIEW);
+
+ const clearPayload = {
+ assetLinks: null,
+ appleAppSiteAssociation: null,
+ deepviewData: null,
+ };
+
+ const { status: clearStatus, data: cleared } =
+ await api.patch<DomainProps>(`/api/domains/${slug}`, clearPayload);
+
+ expect(clearStatus).toEqual(200);
+ expect(cleared.assetLinks).toBeNull();
+ expect(cleared.appleAppSiteAssociation).toBeNull();
+ expect(cleared.deepviewData).toBeNull();
+ } finally {
+ await deleteDomain(api, slug);
+ }
+ });
+});
diff --git a/apps/web/tests/domains/index.test.ts b/apps/web/tests/domains/index.test.ts
deleted file mode 100644
index 0e9a654d68..0000000000
--- a/apps/web/tests/domains/index.test.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-import { DomainStatusSchema } from "@/lib/zod/schemas/domains";
-import { Domain } from "@prisma/client";
-import { describe, expect, onTestFinished, test } from "vitest";
-import * as z from "zod/v4";
-import { randomId } from "../utils/helpers";
-import { IntegrationHarness } from "../utils/integration";
-
-const slug = `${randomId()}.dub-internal-test.com`;
-
-const domainRecord = {
- slug: slug,
- expiredUrl: `https://${slug}/expired`,
- placeholder: `https://${slug}/placeholder`,
- notFoundUrl: `https://${slug}/not-found`,
-};
-
-const expectedDomain = {
- id: expect.any(String),
- slug: domainRecord.slug,
- verified: expect.any(Boolean),
- primary: expect.any(Boolean),
- archived: false,
- placeholder: domainRecord.placeholder,
- expiredUrl: domainRecord.expiredUrl,
- notFoundUrl: domainRecord.notFoundUrl,
- createdAt: expect.any(String),
- updatedAt: expect.any(String),
- registeredDomain: null,
- logo: null,
- appleAppSiteAssociation: null,
- assetLinks: null,
- deepviewData: "{}",
-};
-
-describe.sequential("/domains/**", async () => {
- const h = new IntegrationHarness();
- const { workspace, http } = await h.init();
-
- test("POST /domains", async () => {
- const { status, data: domain } = await http.post<Domain>({
- path: "/domains",
- query: { workspaceId: workspace.id },
- body: domainRecord,
- });
-
- expect(status).toEqual(201);
- expect(domain).toStrictEqual(expectedDomain);
- });
-
- test("GET /domains/{slug}", async () => {
- const { status, data: domain } = await http.get<Domain>({
- path: `/domains/${domainRecord.slug}`,
- query: { workspaceId: workspace.id },
- });
-
- expect(status).toEqual(200);
- expect(domain).toStrictEqual(expectedDomain);
- });
-
- test("GET /domains", async () => {
- const { status, data: domains } = await http.get<Domain[]>({
- path: "/domains",
- query: { workspaceId: workspace.id },
- });
-
- expect(status).toEqual(200);
- expect(
- domains.map((d) => ({ ...d, registeredDomain: null })),
- ).toContainEqual(expectedDomain);
- });
-
- test("POST /domains/{slug}/primary", { retry: 3 }, async () => {
- const { status, data: domain } = await http.post<Domain>({
- path: `/domains/${domainRecord.slug}/primary`,
- query: { workspaceId: workspace.id },
- });
-
- expect(status).toEqual(200);
- expect(domain).toStrictEqual({
- ...expectedDomain,
- primary: true,
- });
-
- onTestFinished(async () => {
- // reset the primary domain
- await http.post<Domain>({
- path: "/domains/getacme.link/primary",
- query: { workspaceId: workspace.id },
- });
- });
- });
-
- test("PATCH /domains/{slug}", { retry: 3 }, async () => {
- const toUpdate = {
- expiredUrl: `https://${slug}/expired-new`,
- placeholder: `https://${slug}/placeholder-new`,
- notFoundUrl: `https://${slug}/not-found-new`,
- archived: true,
- };
-
- onTestFinished(async () => {
- await h.deleteDomain(domainRecord.slug);
- });
-
- const { status, data: domain } = await http.patch<Domain>({
- path: `/domains/${domainRecord.slug}`,
- query: { workspaceId: workspace.id },
- body: toUpdate,
- });
-
- expect(status).toEqual(200);
- expect(domain).toStrictEqual({
- ...expectedDomain,
- ...toUpdate,
- });
- });
-
- test("GET /domains/status", async () => {
- const domains = [
- "getacme.link", // expected to be unavailable
- `acme-${randomId(4).toLowerCase()}.link`, // expected to be available
- ];
-
- const { status, data: domainStatuses } = await http.get<
- z.infer<typeof DomainStatusSchema>[]
- >({
- path: "/domains/status",
- query: {
- workspaceId: workspace.id,
- domains: domains.join(","),
- },
- });
-
- expect(status).toEqual(200);
- expect(domainStatuses).toHaveLength(2);
- expect(domainStatuses).toEqual([
- {
- domain: domains[0],
- available: false,
- premium: null,
- prices: null,
- price: null,
- },
- {
- domain: domains[1],
- available: true,
- premium: expect.any(Boolean),
- prices: {
- registration: expect.any(Number),
- renewal: expect.any(Number),
- },
- price: expect.any(String),
- },
- ]);
- });
-});