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.

Add social media verification functionality (#3315)

Kiran Kb68c970d308c
diff --git a/apps/web/.env.example b/apps/web/.env.example
index 5d929034b2..f9bc4d7a92 100644
--- a/apps/web/.env.example
+++ b/apps/web/.env.example
@@ -6,13 +6,13 @@ NEXT_PUBLIC_APP_NAME=Dub
NEXT_PUBLIC_APP_DOMAIN=dub.co
NEXT_PUBLIC_APP_SHORT_DOMAIN=dub.sh
-# Tinybird – required for analytics
+# Tinybird – required for analytics
# Get your Tinybird Auth Token here: https://www.tinybird.co/docs/concepts/auth-tokens.html
TINYBIRD_API_KEY=
# Varies based on your Tinybird region: https://www.tinybird.co/docs/api-reference/api-reference.html#regions-and-endpoints
TINYBIRD_API_URL=https://api.tinybird.co
-# Vercel's Domains API – required for adding and removing domains
+# Vercel's Domains API – required for adding and removing domains
# Learn how to set this up: https://vercel.com/templates/next.js/domains-api
PROJECT_ID_VERCEL=
TEAM_ID_VERCEL=
@@ -23,7 +23,7 @@ AUTH_BEARER_TOKEN=
UPSTASH_REDIS_REST_URL=
UPSTASH_REDIS_REST_TOKEN=
-# Upstash QStash – required for queues and background jobs
+# Upstash QStash – required for queues and background jobs
# Get your QStash Token here: https://upstash.com/docs/qstash/overall/getstarted
QSTASH_TOKEN=
QSTASH_CURRENT_SIGNING_KEY=
@@ -42,6 +42,8 @@ NEXTAUTH_URL=http://localhost:8888 # (only needed for localhost)
# Required for email login
# Get your Resend API Key here: https://resend.com/api-keys
RESEND_API_KEY=
+# Resend webhook secret for webhook verification
+RESEND_WEBHOOK_SECRET=
# SMTP configuration (Recommended for local development)
SMTP_HOST=localhost
@@ -49,11 +51,14 @@ SMTP_PORT=1025
SMTP_USER=smtpUser
SMTP_PASSWORD=smtpPassword
+# Email unsubscribe token secret (optional, falls back to NEXTAUTH_SECRET)
+UNSUBSCRIBE_TOKEN_SECRET=
+
###############################
###### OPTIONAL ENV VARS ######
###############################
-# Stripe – used for subscriptions
+# Stripe – used for subscriptions
# If you don't need this, you can also remove the `lib/stripe` folder and all instances of `stripe` from the codebase
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
STRIPE_SECRET_KEY=
@@ -75,7 +80,11 @@ GOOGLE_CLIENT_SECRET=
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
-# Edge Config – used for admin features like banning users, rate limiting etc.
+# Used for Framer Login
+FRAMER_CLIENT_ID=
+FRAMER_CLIENT_SECRET=
+
+# Edge Config – used for admin features like banning users, rate limiting etc.
# Create one here: https://vercel.com/docs/storage/edge-config
# Alternatively, if you don't need this, you can also remove `lib/edge-config.ts`
# and all instances of `EDGE_CONFIG` and `EDGE_CONFIG_ID` from the codebase
@@ -111,6 +120,16 @@ NEXT_PUBLIC_NGROK_URL=
# For AI features
ANTHROPIC_API_KEY=
+# Axiom – used for logging and monitoring
+# Get your Axiom token here: https://axiom.co/docs/rest-api/authentication
+AXIOM_TOKEN=
+AXIOM_DATASET=
+
+# Plain – used for customer support integration
+# Get your Plain API key here: https://www.plain.com/docs/api
+PLAIN_API_KEY=
+PLAIN_WEBHOOK_SECRET=
+
######################################
###### DUB.CO INTERNAL USE ONLY ######
######################################
@@ -129,14 +148,19 @@ SLACK_SIGNING_SECRET=
# Dynadot API key for domain registration
DYNADOT_API_KEY=
DYNADOT_BASE_URL=
+DYNADOT_COUPON=
# Online Presence Verification
-YOUTUBE_CLIENT_ID=
-YOUTUBE_CLIENT_SECRET=
-X_CLIENT_ID=
-X_CLIENT_SECRET=
+TWITTER_CLIENT_ID=
+TWITTER_CLIENT_SECRET=
TIKTOK_CLIENT_ID=
TIKTOK_CLIENT_SECRET=
+LINKEDIN_CLIENT_ID=
+LINKEDIN_CLIENT_SECRET=
+YOUTUBE_API_KEY=
+
+# Scrape Creators
+SCRAPECREATORS_API_KEY=
# Paypal
PAYPAL_CLIENT_ID=
@@ -146,6 +170,7 @@ PAYPAL_WEBHOOK_ID=
# Stripe Integration
STRIPE_APP_SECRET_KEY_TEST=
STRIPE_APP_SECRET_KEY=
+STRIPE_APP_SECRET_KEY_SANDBOX=
# Program lander generation
FIRECRAWL_API_KEY=
diff --git a/apps/web/app/(ee)/api/cron/auto-approve-partner/route.ts b/apps/web/app/(ee)/api/cron/auto-approve-partner/route.ts
index 98b2633622..e4b2d736a1 100644
--- a/apps/web/app/(ee)/api/cron/auto-approve-partner/route.ts
+++ b/apps/web/app/(ee)/api/cron/auto-approve-partner/route.ts
@@ -18,37 +18,23 @@ const schema = z.object({
export const POST = withCron(async ({ rawBody }) => {
const { programId, partnerId } = schema.parse(JSON.parse(rawBody));
- const program = await prisma.program.findUniqueOrThrow({
+ const programEnrollment = await prisma.programEnrollment.findUnique({
where: {
- id: programId,
+ partnerId_programId: {
+ partnerId,
+ programId,
+ },
},
include: {
- workspace: {
+ partnerGroup: true,
+ partner: {
include: {
- users: {
- where: {
- role: "owner",
- },
- take: 1,
- },
- },
- },
- partners: {
- where: {
- partnerId,
- },
- select: {
- partnerGroup: true,
- groupId: true,
- status: true,
- partner: true,
+ platforms: true,
},
},
},
});
- const programEnrollment = program.partners[0];
-
if (!programEnrollment) {
return logAndRespond(
`Partner ${partnerId} not found in program ${programId}. Skipping auto-approval.`,
@@ -77,6 +63,24 @@ export const POST = withCron(async ({ rawBody }) => {
// Check if the workspace plan has fraud event management capabilities
// If enabled, we'll evaluate risk signals before auto-approving
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ include: {
+ workspace: {
+ include: {
+ users: {
+ where: {
+ role: "owner",
+ },
+ take: 1,
+ },
+ },
+ },
+ },
+ });
+
const { canManageFraudEvents } = getPlanCapabilities(program.workspace.plan);
if (canManageFraudEvents) {
diff --git a/apps/web/app/(ee)/api/cron/online-presence/youtube/route.ts b/apps/web/app/(ee)/api/cron/online-presence/youtube/route.ts
index f6077fa45a..25692a17f7 100644
--- a/apps/web/app/(ee)/api/cron/online-presence/youtube/route.ts
+++ b/apps/web/app/(ee)/api/cron/online-presence/youtube/route.ts
@@ -1,8 +1,18 @@
-import { handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { withCron } from "@/lib/cron/with-cron";
import { prisma } from "@dub/prisma";
+import { PlatformType } from "@dub/prisma/client";
import { chunk, deepEqual } from "@dub/utils";
-import { NextResponse } from "next/server";
+import { z } from "zod";
+import { logAndRespond } from "../../utils";
+
+const youtubeChannelSchema = z.object({
+ id: z.string(),
+ statistics: z.object({
+ videoCount: z.string().transform((val) => parseInt(val, 10)),
+ subscriberCount: z.string().transform((val) => parseInt(val, 10)),
+ viewCount: z.string().transform((val) => parseInt(val, 10)),
+ }),
+});
export const dynamic = "force-dynamic";
@@ -10,105 +20,93 @@ export const dynamic = "force-dynamic";
This route is used to update youtube stats for youtubeVerified partners
Runs once a day at 06:00 AM UTC (cron expression: 0 6 * * *)
*/
-export async function POST(req: Request) {
- try {
- const rawBody = await req.text();
+export const POST = withCron(async () => {
+ if (!process.env.YOUTUBE_API_KEY) {
+ throw new Error("YOUTUBE_API_KEY is not defined");
+ }
+
+ const youtubeChannels = await prisma.partnerPlatform.findMany({
+ where: {
+ type: PlatformType.youtube,
+ verifiedAt: {
+ not: null,
+ },
+ platformId: {
+ not: null,
+ },
+ },
+ });
+
+ if (youtubeChannels.length === 0) {
+ return logAndRespond(
+ "No YouTube platforms found. Skipping YouTube stats update.",
+ );
+ }
- await verifyQstashSignature({
- req,
- rawBody,
- });
+ const chunks = chunk(youtubeChannels, 50);
- if (!process.env.YOUTUBE_API_KEY) {
- throw new Error("YOUTUBE_API_KEY is not defined");
+ for (const chunk of chunks) {
+ const channelIds = chunk.map((channel) => channel.platformId);
+
+ if (channelIds.length === 0) {
+ continue;
}
- const youtubeVerifiedPartners = await prisma.partner.findMany({
- where: {
- youtubeChannelId: {
- not: null,
- },
- youtubeVerifiedAt: {
- not: null,
+ const response = await fetch(
+ `https://www.googleapis.com/youtube/v3/channels?part=statistics,snippet&id=${channelIds.join(",")}`,
+ {
+ headers: {
+ "X-Goog-Api-Key": process.env.YOUTUBE_API_KEY,
},
},
- select: {
- id: true,
- email: true,
- youtube: true,
- youtubeChannelId: true,
- youtubeSubscriberCount: true,
- youtubeVideoCount: true,
- youtubeViewCount: true,
- },
- });
+ );
- const chunks = chunk(youtubeVerifiedPartners, 50);
+ if (!response.ok) {
+ console.error("Failed to fetch YouTube data:", await response.text());
+ continue;
+ }
- for (const chunk of chunks) {
- const channelIds = chunk.map(
- (partner) => partner.youtubeChannelId as string,
- );
+ const data = await response.json().then((r) => r.items);
+ const channels = z.array(youtubeChannelSchema).parse(data);
- if (channelIds.length === 0) continue;
+ for (const channel of channels) {
+ const partnerPlatform = chunk.find((p) => p.platformId === channel.id);
- const response = await fetch(
- `https://www.googleapis.com/youtube/v3/channels?part=statistics,snippet&id=${channelIds.join(",")}`,
- {
- headers: {
- "X-Goog-Api-Key": process.env.YOUTUBE_API_KEY,
- },
- },
- );
-
- if (!response.ok) {
- console.error("Failed to fetch YouTube data:", await response.text());
+ if (!partnerPlatform) {
continue;
}
- const data = await response.json().then((r) => r.items);
-
- for (const d of data) {
- const partner = chunk.find((p) => p.youtubeChannelId === d.id);
-
- if (!partner || !d.statistics) {
- continue;
- }
-
- const { viewCount, subscriberCount, videoCount } = d.statistics;
-
- // Only compare the YouTube stats
- const currentStats = {
- youtubeSubscriberCount: partner.youtubeSubscriberCount,
- youtubeVideoCount: partner.youtubeVideoCount,
- youtubeViewCount: partner.youtubeViewCount,
- };
-
- const newStats = {
- youtubeSubscriberCount: parseInt(subscriberCount || "0", 10),
- youtubeVideoCount: parseInt(videoCount || "0", 10),
- youtubeViewCount: parseInt(viewCount || "0", 10),
- };
-
- if (deepEqual(currentStats, newStats)) {
- continue;
- }
-
- await prisma.partner.update({
- where: { id: partner.id },
- data: newStats,
- });
- console.log(
- `Updated YouTube stats for ${partner.email} (@${partner.youtube})`,
- newStats,
- );
+ const currentStats = {
+ subscribers: partnerPlatform.subscribers,
+ posts: partnerPlatform.posts,
+ views: partnerPlatform.views,
+ };
+
+ const newStats = {
+ subscribers: channel.statistics.subscriberCount,
+ posts: channel.statistics.videoCount,
+ views: channel.statistics.viewCount,
+ };
+
+ if (deepEqual(currentStats, newStats)) {
+ continue;
}
- }
- return NextResponse.json({
- message: `YouTube stats updated for ${youtubeVerifiedPartners.length} partners`,
- });
- } catch (error) {
- return handleAndReturnErrorResponse(error);
+ await prisma.partnerPlatform.update({
+ where: {
+ id: partnerPlatform.id,
+ },
+ data: newStats,
+ });
+
+ console.log(
+ `Updated YouTube stats for @${partnerPlatform.identifier}`,
+ newStats,
+ );
+ }
}
-}
+
+ return logAndRespond(
+ `YouTube stats updated for ${youtubeChannels.length} partners`,
+ );
+});
diff --git a/apps/web/app/(ee)/api/partners/[partnerId]/application-risks/route.ts b/apps/web/app/(ee)/api/partners/[partnerId]/application-risks/route.ts
index 9a60871959..37eafea7df 100644
--- a/apps/web/app/(ee)/api/partners/[partnerId]/application-risks/route.ts
+++ b/apps/web/app/(ee)/api/partners/[partnerId]/application-risks/route.ts
@@ -14,7 +14,11 @@ export const GET = withWorkspace(
partnerId,
programId,
include: {
- partner: true,
+ partner: {
+ include: {
+ platforms: true,
+ },
+ },
},
});
diff --git a/apps/web/app/(ee)/api/partners/online-presence/callback/route.ts b/apps/web/app/(ee)/api/partners/online-presence/callback/route.ts
index cd35079f2b..a875f1f74a 100644
--- a/apps/web/app/(ee)/api/partners/online-presence/callback/route.ts
+++ b/apps/web/app/(ee)/api/partners/online-presence/callback/route.ts
@@ -1,144 +1,170 @@
-import { ONLINE_PRESENCE_PROVIDERS } from "@/lib/actions/partners/online-presence-providers";
+import { ONLINE_PRESENCE_PROVIDERS } from "@/lib/api/partner-profile/online-presence-providers";
+import { getSession } from "@/lib/auth/utils";
+import { redis } from "@/lib/upstash/redis";
import { prisma } from "@dub/prisma";
-import { PARTNERS_DOMAIN, PARTNERS_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { PlatformType } from "@dub/prisma/client";
+import {
+ getSearchParams,
+ PARTNERS_DOMAIN,
+ PARTNERS_DOMAIN_WITH_NGROK,
+} from "@dub/utils";
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
+import { z } from "zod";
+const requestSchema = z.object({
+ code: z.string(),
+ state: z.string(),
+});
+
+interface State {
+ platform: PlatformType;
+ partnerId: string;
+ source: "onboarding" | "settings";
+}
+
+// GET /api/partners/online-presence/callback
export async function GET(req: Request) {
const { searchParams } = new URL(req.url);
- // get code and workspace id from query params
- const code = searchParams.get("code") as string;
- const state = searchParams.get("state") as string;
- if (!state) {
- console.warn("No state found in OAuth callback");
+ // Validate the request
+ const parsedSearchParams = requestSchema.safeParse(getSearchParams(req.url));
+
+ if (!parsedSearchParams.success) {
+ console.warn("Missing required search params in OAuth callback.");
return NextResponse.redirect(PARTNERS_DOMAIN);
}
- let redirectUrl = getRedirectUrl("onboarding");
+ const { code, state } = parsedSearchParams.data;
+
+ // Get current user
+ const session = await getSession();
+
+ if (!session?.user?.id) {
+ console.warn("Unauthorized: Login required.");
+ return NextResponse.redirect(PARTNERS_DOMAIN);
+ }
- let stateObject: any = {};
+ // Find the state from Redis
+ const stateFromRedis = await redis.get<State>(
+ `partnerSocialVerification:${state}`,
+ );
- try {
- stateObject = JSON.parse(Buffer.from(state, "base64").toString("ascii"));
- } catch (e) {
- console.warn("Failed to parse state in OAuth callback");
+ if (!stateFromRedis) {
+ console.warn("State is invalid or expired.");
return NextResponse.redirect(PARTNERS_DOMAIN);
}
- const { provider, partnerId, source } = stateObject;
+ const { platform, partnerId, source } = stateFromRedis;
- redirectUrl = getRedirectUrl(source);
+ if (session.user.defaultPartnerId !== partnerId) {
+ console.warn("Unauthorized: User is not the default partner.");
+ return NextResponse.redirect(PARTNERS_DOMAIN);
+ }
+
+ // Validate platform exists in providers
+ const provider = ONLINE_PRESENCE_PROVIDERS[platform];
+ if (!provider) {
+ console.error(`Invalid platform: ${platform}`);
+ return NextResponse.redirect(PARTNERS_DOMAIN);
+ }
+
+ // Redirect user based on source
+ const redirectUrl =
+ source === "onboarding"
+ ? `${PARTNERS_DOMAIN}/onboarding/online-presence`
+ : `${PARTNERS_DOMAIN}/profile`;
+
+ const { tokenUrl, clientId, clientSecret, verify, pkce, clientIdParam } =
+ provider;
+
+ const cookieStore = await cookies();
+ const codeVerifier = pkce
+ ? cookieStore.get("online_presence_code_verifier")?.value
+ : null;
+
+ // Local development redirect since the verifier cookie won't be present on ngrok
+ if (pkce && !codeVerifier && process.env.NODE_ENV === "development") {
+ return NextResponse.redirect(
+ `http://partners.localhost:8888/api/partners/online-presence/callback?${searchParams.toString()}`,
+ );
+ }
- if (!code) {
- console.warn("No code found in OAuth callback");
+ // Remove the state from Redis
+ await redis.del(`partnerSocialVerification:${state}`);
+
+ // Get access token
+ const urlParams = new URLSearchParams({
+ [clientIdParam ?? "client_id"]: clientId!,
+ client_secret: clientSecret!,
+ code,
+ redirect_uri: `${PARTNERS_DOMAIN_WITH_NGROK}/api/partners/online-presence/callback`,
+ grant_type: "authorization_code",
+ ...(codeVerifier && { code_verifier: codeVerifier }),
+ });
+
+ const response = await fetch(tokenUrl, {
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded",
+ Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`,
+ },
+ method: "POST",
+ body: urlParams.toString(),
+ });
+
+ const tokenResponse = await response.json();
+
+ if (!response.ok) {
+ console.warn("Failed to get access token in OAuth callback", tokenResponse);
return NextResponse.redirect(redirectUrl);
}
- try {
- if (!provider || !ONLINE_PRESENCE_PROVIDERS?.[provider]) {
- console.error("No provider found in OAuth callback state");
- return NextResponse.redirect(redirectUrl);
- }
-
- if (!partnerId) {
- console.error("No partnerId found in OAuth callback state");
- return NextResponse.redirect(redirectUrl);
- }
-
- const {
- tokenUrl,
- clientId,
- clientSecret,
- verify,
- verifiedColumn,
- pkce,
- clientIdParam,
- } = ONLINE_PRESENCE_PROVIDERS[provider];
-
- // Get code verifier from cookie if this is X/Twitter
- const codeVerifier = pkce
- ? (await cookies()).get("online_presence_code_verifier")?.value
- : null;
-
- // Local development redirect since the verifier cookie won't be present on ngrok
- if (pkce && !codeVerifier && process.env.NODE_ENV === "development") {
- return NextResponse.redirect(
- `http://partners.localhost:8888/api/partners/online-presence/callback?${searchParams.toString()}`,
- );
- }
-
- // Get access token
- const result = await fetch(tokenUrl, {
- method: "POST",
- headers: {
- "Content-Type": "application/x-www-form-urlencoded",
- Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`,
- },
- body: new URLSearchParams({
- [clientIdParam ?? "client_id"]: clientId!,
- client_secret: clientSecret!,
- code,
- redirect_uri: `${PARTNERS_DOMAIN_WITH_NGROK}/api/partners/online-presence/callback`,
- grant_type: "authorization_code",
- ...(codeVerifier && { code_verifier: codeVerifier }),
- }).toString(),
- }).then(async (r) => {
- const text = await r.text();
- try {
- return JSON.parse(text);
- } catch (e) {
- console.error("Failed to parse access token response", text);
- throw e;
- }
- });
-
- if (!result || !result.access_token) {
- console.warn("No access token found in OAuth callback");
- return NextResponse.redirect(redirectUrl);
- }
-
- const partner = await prisma.partner.findUniqueOrThrow({
- where: {
- id: partnerId,
+ if (!tokenResponse.access_token) {
+ console.warn("No access token found in OAuth callback");
+ return NextResponse.redirect(redirectUrl);
+ }
+
+ const partnerPlatform = await prisma.partnerPlatform.findUnique({
+ where: {
+ partnerId_type: {
+ partnerId,
+ type: platform,
},
- });
-
- const { verified: isVerified, metadata } = await verify({
- partner,
- accessToken: result.access_token,
- });
-
- if (isVerified) {
- await prisma.partner.update({
- where: {
- id: partnerId,
- },
- data: {
- [provider]: partner[provider],
- [verifiedColumn]: new Date(),
- ...(provider === "youtube" &&
- metadata && {
- youtubeChannelId: metadata.channelId,
- youtubeSubscriberCount: parseInt(
- metadata.subscriberCount || "0",
- 10,
- ),
- youtubeVideoCount: parseInt(metadata.videoCount || "0", 10),
- youtubeViewCount: parseInt(metadata.viewCount || "0", 10),
- }),
- },
- });
- }
+ },
+ });
+ if (!partnerPlatform || !partnerPlatform.identifier) {
+ console.error("No partner platform found in OAuth callback");
return NextResponse.redirect(redirectUrl);
- } catch (error) {
- console.error("Error in online presence OAuth callback", error);
- return NextResponse.redirect(PARTNERS_DOMAIN);
}
-}
-const getRedirectUrl = (source: string) =>
- source === "onboarding"
- ? `${PARTNERS_DOMAIN}/onboarding/online-presence`
- : `${PARTNERS_DOMAIN}/profile`;
+ const { verified, metadata } = await verify({
+ handle: partnerPlatform.identifier,
+ accessToken: tokenResponse.access_token,
+ });
+
+ if (!verified) {
+ console.warn("Failed to verify social account in OAuth callback");
+ return NextResponse.redirect(redirectUrl);
+ }
+
+ await prisma.partnerPlatform.update({
+ where: {
+ partnerId_type: {
+ partnerId,
+ type: platform,
+ },
+ },
+ data: {
+ verifiedAt: new Date(),
+ metadata: metadata || undefined,
+ },
+ });
+
+ // Delete PKCE code verifier cookie after successful use
+ if (pkce && codeVerifier) {
+ cookieStore.delete("online_presence_code_verifier");
+ }
+
+ return NextResponse.redirect(redirectUrl);
+}
diff --git a/apps/web/app/(ee)/api/partners/route.ts b/apps/web/app/(ee)/api/partners/route.ts
index 5b39b2dc49..41bf55b8af 100644
--- a/apps/web/app/(ee)/api/partners/route.ts
+++ b/apps/web/app/(ee)/api/partners/route.ts
@@ -4,10 +4,12 @@ import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-progr
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
+import { polyfillSocialMediaFields } from "@/lib/social-utils";
import {
createPartnerSchema,
EnrolledPartnerSchema,
getPartnersQuerySchemaExtended,
+ partnerPlatformSchema,
} from "@/lib/zod/schemas/partners";
import { NextResponse } from "next/server";
import * as z from "zod/v4";
@@ -18,7 +20,7 @@ export const GET = withWorkspace(
const programId = getDefaultProgramIdOrThrow(workspace);
const {
sortBy: sortByWithOldFields,
- includeOnlinePresenceVerification,
+ includePartnerPlatforms,
...parsedParams
} = getPartnersQuerySchemaExtended
.extend({
@@ -64,15 +66,9 @@ export const GET = withWorkspace(
saleAmount: z.number().default(0),
});
- // Whether to include online presence verification fields (websiteVerifiedAt, youtubeVerifiedAt, etc.) in the response.
- const responseSchema = includeOnlinePresenceVerification
+ const responseSchema = includePartnerPlatforms
? baseSchema.extend({
- websiteVerifiedAt: z.date().nullish(),
- youtubeVerifiedAt: z.date().nullish(),
- twitterVerifiedAt: z.date().nullish(),
- linkedinVerifiedAt: z.date().nullish(),
- instagramVerifiedAt: z.date().nullish(),
- tiktokVerifiedAt: z.date().nullish(),
+ platforms: z.array(partnerPlatformSchema),
})
: baseSchema;
@@ -85,6 +81,7 @@ export const GET = withWorkspace(
conversions: partner.totalConversions,
sales: partner.totalSales,
saleAmount: partner.totalSaleAmount,
+ ...polyfillSocialMediaFields(partner.platforms),
})),
),
);
diff --git a/apps/web/app/(ee)/api/workflows/partner-approved/route.ts b/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
index 10b033c2db..6358648e47 100644
--- a/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
+++ b/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
@@ -1,11 +1,11 @@
import { triggerDraftBountySubmissionCreation } from "@/lib/api/bounties/trigger-draft-bounty-submissions";
-import { getGroupOrThrow } from "@/lib/api/groups/get-group-or-throw";
import { createPartnerDefaultLinks } from "@/lib/api/partners/create-partner-default-links";
import { getPartnerInviteRewardsAndBounties } from "@/lib/api/partners/get-partner-invite-rewards-and-bounties";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
import { createWorkflowLogger } from "@/lib/cron/qstash-workflow-logger";
-import { PlanProps, RewardProps } from "@/lib/types";
+import { polyfillSocialMediaFields } from "@/lib/social-utils";
+import { PlanProps } from "@/lib/types";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { EnrolledPartnerSchema } from "@/lib/zod/schemas/partners";
import { sendBatchEmail } from "@dub/email";
@@ -197,19 +197,6 @@ export const { POST } = serve<Payload>(
return;
}
- // Find the group to get the rewards
- const group = await getGroupOrThrow({
- programId,
- groupId,
- includeExpandedFields: true,
- });
-
- const rewards = [
- group.clickReward,
- group.leadReward,
- group.saleReward,
- ].filter(Boolean) as RewardProps[];
-
logger.info({
message: `Sending email notification to ${partnerUsers.length} partner users.`,
data: partnerUsers,
@@ -265,9 +252,16 @@ export const { POST } = serve<Payload>(
data: input,
});
+ const partnerPlatforms = await prisma.partnerPlatform.findMany({
+ where: {
+ partnerId,
+ },
+ });
+
const enrolledPartner = EnrolledPartnerSchema.parse({
...programEnrollment,
...partner,
+ ...polyfillSocialMediaFields(partnerPlatforms),
id: partner.id,
status: programEnrollment.status,
links,
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx
index 8989bebbd8..1bc9f6f6ad 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx
@@ -102,7 +102,7 @@ export function ProfileDetailsForm({ partner }: { partner?: PartnerProps }) {
<SettingsRow
id="sites"
heading="Website and socials"
- description="Add your website and social accounts you use to share links. Verifying at least one helps build trust with programs."
+ description="Add your website and social accounts you use to share links. Verifying as many platforms as possible helps build trust with programs."
>
<OnlinePresenceForm
ref={onlinePresenceFormRef}
diff --git a/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/online-presence/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/online-presence/page-client.tsx
index bdae15ae14..af2745661d 100644
--- a/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/online-presence/page-client.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/online-presence/page-client.tsx
@@ -1,23 +1,27 @@
"use client";
+import { PartnerProps } from "@/lib/types";
import { OnlinePresenceForm } from "@/ui/partners/online-presence-form";
import Link from "next/link";
import { useRouter } from "next/navigation";
-import { ComponentProps } from "react";
export function OnlinePresencePageClient({
- country,
- ...rest
-}: { country: string | null } & ComponentProps<typeof OnlinePresenceForm>) {
+ partner,
+}: {
+ partner: Pick<PartnerProps, "country" | "platforms">;
+}) {
const router = useRouter();
return (
<>
<OnlinePresenceForm
onSubmitSuccessful={() =>
- router.push(country === "US" ? "/onboarding/verify" : "/programs")
+ router.push(
+ partner.country === "US" ? "/onboarding/verify" : "/programs",
+ )
}
- {...rest}
+ partner={partner}
+ variant="onboarding"
/>
<Link
href="/onboarding/verify"
diff --git a/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/online-presence/page.tsx b/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/online-presence/page.tsx
index 5778b5f2f1..0a76102960 100644
--- a/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/online-presence/page.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(onboarding)/onboarding/online-presence/page.tsx
@@ -1,7 +1,12 @@
import { getSession } from "@/lib/auth";
+import { buildSocialPlatformLookup } from "@/lib/social-utils";
+import { PartnerPlatformProps } from "@/lib/types";
+import { partnerPlatformSchema } from "@/lib/zod/schemas/partners";
import { OnlinePresenceForm } from "@/ui/partners/online-presence-form";
import { prisma } from "@dub/prisma";
+import { PlatformType } from "@dub/prisma/client";
import { Suspense } from "react";
+import { z } from "zod";
import { OnlinePresencePageClient } from "./page-client";
export default function OnlinePresencePage() {
@@ -40,14 +45,10 @@ async function OnlinePresenceFormRSC() {
select: {
email: true,
country: true,
- website: true,
- youtube: true,
- twitter: true,
- linkedin: true,
- instagram: true,
- tiktok: true,
+ platforms: true,
},
}),
+
prisma.programApplication.findFirst({
where: {
enrollment: {
@@ -78,30 +79,40 @@ async function OnlinePresenceFormRSC() {
throw new Error("Partner not found");
}
- return (
- <OnlinePresencePageClient
- country={partner.country}
- partner={{
- ...partner,
- ...(application?.website && !partner.website
- ? { website: application?.website }
- : {}),
- ...(application?.tiktok && !partner.tiktok
- ? { tiktok: application?.tiktok }
- : {}),
- ...(application?.youtube && !partner.youtube
- ? { youtube: application?.youtube }
- : {}),
- ...(application?.twitter && !partner.twitter
- ? { twitter: application?.twitter }
- : {}),
- ...(application?.linkedin && !partner.linkedin
- ? { linkedin: application?.linkedin }
- : {}),
- ...(application?.instagram && !partner.instagram
- ? { instagram: application?.instagram }
- : {}),
- }}
- />
- );
+ // Merge social handles from a partner application into the partner platforms list.
+ const platforms: PartnerPlatformProps[] = z
+ .array(partnerPlatformSchema)
+ .parse(partner.platforms);
+
+ if (application) {
+ const socialPlatformsMap = buildSocialPlatformLookup(platforms);
+
+ const APPLICATION_SOCIAL_PLATFORMS = [
+ "website",
+ "youtube",
+ "twitter",
+ "linkedin",
+ "instagram",
+ "tiktok",
+ ] as const satisfies readonly PlatformType[];
+
+ for (const platform of APPLICATION_SOCIAL_PLATFORMS) {
+ const handle = application[platform];
+
+ // Application-provided handles are added only if the partner does not already have that platform.
+ if (handle && !socialPlatformsMap[platform]) {
+ platforms.push({
+ type: platform,
+ identifier: handle,
+ platformId: null,
+ verifiedAt: null,
+ subscribers: BigInt(0),
+ views: BigInt(0),
+ posts: BigInt(0),
+ });
+ }
+ }
+ }
+
+ return <OnlinePresencePageClient partner={{ ...partner, platforms }} />;
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/network/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/network/page-client.tsx
index 213e0a177b..9f2f39c186 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/network/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/network/page-client.tsx
@@ -386,7 +386,7 @@ function PartnerCard({
? ONLINE_PRESENCE_FIELDS.map((field) => ({
label: field.label,
icon: field.icon,
- ...field.data(partner),
+ ...field.data(partner.platforms),
})).filter((field) => field.value && field.href)
: null,
[partner],
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/page-client.tsx
index 5e1ce3945f..9117a04468 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/page-client.tsx
@@ -1,11 +1,12 @@
"use client";
+import { buildSocialPlatformLookup } from "@/lib/social-utils";
import { mutatePrefix } from "@/lib/swr/mutate";
import useGroups from "@/lib/swr/use-groups";
import usePartner from "@/lib/swr/use-partner";
import usePartnersCount from "@/lib/swr/use-partners-count";
import useWorkspace from "@/lib/swr/use-workspace";
-import { EnrolledPartnerProps } from "@/lib/types";
+import { EnrolledPartnerProps, PartnerPlatformProps } from "@/lib/types";
import { useBulkApprovePartnersModal } from "@/ui/modals/bulk-approve-partners-modal";
import { useBulkRejectPartnersModal } from "@/ui/modals/bulk-reject-partners-modal";
import { useRejectPartnerApplicationModal } from "@/ui/modals/reject-partner-application-modal";
@@ -15,6 +16,7 @@ import { PartnerRowItem } from "@/ui/partners/partner-row-item";
import { PartnerSocialColumn } from "@/ui/partners/partner-social-column";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
import { SearchBoxPersisted } from "@/ui/shared/search-box";
+import { PlatformType } from "@dub/prisma/client";
import {
AnimatedSizeContainer,
Button,
@@ -29,12 +31,7 @@ import {
useTable,
} from "@dub/ui";
import { Dots, Users, UserXmark } from "@dub/ui/icons";
-import {
- COUNTRIES,
- fetcher,
- formatDate,
- getDomainWithoutWWW,
-} from "@dub/utils";
+import { COUNTRIES, fetcher, formatDate } from "@dub/utils";
import { Row } from "@tanstack/react-table";
import { Command } from "cmdk";
import { useEffect, useMemo, useState } from "react";
@@ -98,7 +95,7 @@ export function ProgramPartnersApplicationsPageClient() {
status: "pending",
sortBy,
sortOrder,
- includeOnlinePresenceVerification: true,
+ includePartnerPlatforms: true,
},
{ exclude: ["partnerId"] },
)}`,
@@ -111,6 +108,21 @@ export function ProgramPartnersApplicationsPageClient() {
const { groups } = useGroups();
+ // Create a separate map for platform lookups by partner ID
+ const platformsMapByPartnerId = useMemo(() => {
+ const map = new Map<
+ string,
+ Record<PlatformType, PartnerPlatformProps | null>
+ >();
+
+ partners?.forEach((partner) => {
+ if (partner.platforms) {
+ map.set(partner.id, buildSocialPlatformLookup(partner.platforms));
+ }
+ });
+ return map;
+ }, [partners]);
+
const [detailsSheetState, setDetailsSheetState] = useState<
| { open: false; partnerId: string | null }
| { open: true; partnerId: string }
@@ -230,11 +242,13 @@ export function ProgramPartnersApplicationsPageClient() {
id: "website",
header: "Website",
minSize: 150,
- cell: ({ row }) => {
+ cell: ({ row }: { row: Row<EnrolledPartnerProps> }) => {
+ const platformsMap = platformsMapByPartnerId.get(row.original.id);
+
return (
<PartnerSocialColumn
- value={getDomainWithoutWWW(row.original.website) ?? "-"}
- verified={!!row.original.websiteVerifiedAt}
+ platform={platformsMap?.website}
+ platformName="website"
/>
);
},
@@ -243,12 +257,13 @@ export function ProgramPartnersApplicationsPageClient() {
id: "youtube",
header: "YouTube",
minSize: 150,
- cell: ({ row }) => {
+ cell: ({ row }: { row: Row<EnrolledPartnerProps> }) => {
+ const platformsMap = platformsMapByPartnerId.get(row.original.id);
+
return (
<PartnerSocialColumn
- at
- value={row.original.youtube}
- verified={!!row.original.youtubeVerifiedAt}
+ platform={platformsMap?.youtube}
+ platformName="youtube"
/>
);
},
@@ -257,12 +272,13 @@ export function ProgramPartnersApplicationsPageClient() {
id: "twitter",
header: "X/Twitter",
minSize: 150,
- cell: ({ row }) => {
+ cell: ({ row }: { row: Row<EnrolledPartnerProps> }) => {
+ const platformsMap = platformsMapByPartnerId.get(row.original.id);
+
return (
<PartnerSocialColumn
- at
- value={row.original.twitter}
- verified={!!row.original.twitterVerifiedAt}
+ platform={platformsMap?.twitter}
+ platformName="twitter"
/>
);
},
@@ -271,11 +287,13 @@ export function ProgramPartnersApplicationsPageClient() {
id: "linkedin",
header: "LinkedIn",
minSize: 150,
- cell: ({ row }) => {
+ cell: ({ row }: { row: Row<EnrolledPartnerProps> }) => {
+ const platformsMap = platformsMapByPartnerId.get(row.original.id);
+
return (
<PartnerSocialColumn
- value={row.original.linkedin}
- verified={!!row.original.linkedinVerifiedAt}
+ platform={platformsMap?.linkedin}
+ platformName="linkedin"
/>
);
},
@@ -284,12 +302,13 @@ export function ProgramPartnersApplicationsPageClient() {
id: "instagram",
header: "Instagram",
minSize: 150,
- cell: ({ row }) => {
+ cell: ({ row }: { row: Row<EnrolledPartnerProps> }) => {
+ const platformsMap = platformsMapByPartnerId.get(row.original.id);
+
return (
<PartnerSocialColumn
- at
- value={row.original.instagram}
- verified={!!row.original.instagramVerifiedAt}
+ platform={platformsMap?.instagram}
+ platformName="instagram"
/>
);
},
@@ -298,12 +317,13 @@ export function ProgramPartnersApplicationsPageClient() {
id: "tiktok",
header: "TikTok",
minSize: 150,
- cell: ({ row }) => {
+ cell: ({ row }: { row: Row<EnrolledPartnerProps> }) => {
+ const platformsMap = platformsMapByPartnerId.get(row.original.id);
+
return (
<PartnerSocialColumn
- at
- value={row.original.tiktok}
- verified={!!row.original.tiktokVerifiedAt}
+ platform={platformsMap?.tiktok}
+ platformName="tiktok"
/>
);
},
@@ -322,7 +342,7 @@ export function ProgramPartnersApplicationsPageClient() {
),
},
],
- [workspaceId, groups],
+ [workspaceId, groups, platformsMapByPartnerId],
);
const { table, ...tableProps } = useTable<EnrolledPartnerProps>({
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/rejected/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/rejected/page-client.tsx
index f54e25084c..a966e7fd1f 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/rejected/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/applications/rejected/page-client.tsx
@@ -1,12 +1,13 @@
"use client";
import { approvePartnerAction } from "@/lib/actions/partners/approve-partner";
+import { buildSocialPlatformLookup } from "@/lib/social-utils";
import { mutatePrefix } from "@/lib/swr/mutate";
import useGroups from "@/lib/swr/use-groups";
import usePartner from "@/lib/swr/use-partner";
import usePartnersCount from "@/lib/swr/use-partners-count";
import useWorkspace from "@/lib/swr/use-workspace";
-import { EnrolledPartnerProps } from "@/lib/types";
+import { EnrolledPartnerProps, PartnerPlatformProps } from "@/lib/types";
import { useConfirmModal } from "@/ui/modals/confirm-modal";
import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
import { PartnerApplicationSheet } from "@/ui/partners/partner-application-sheet";
@@ -14,6 +15,7 @@ import { PartnerRowItem } from "@/ui/partners/partner-row-item";
import { PartnerSocialColumn } from "@/ui/partners/partner-social-column";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
import { SearchBoxPersisted } from "@/ui/shared/search-box";
+import { PlatformType } from "@dub/prisma/client";
import {
AnimatedSizeContainer,
Button,
@@ -28,12 +30,7 @@ import {
useTable,
} from "@dub/ui";
import { Check, Dots, LoadingSpinner, Users } from "@dub/ui/icons";
-import {
- COUNTRIES,
- fetcher,
- formatDate,
- getDomainWithoutWWW,
-} from "@dub/utils";
+import { COUNTRIES, fetcher, formatDate } from "@dub/utils";
import { Row } from "@tanstack/react-table";
import { Command } from "cmdk";
import { useAction } from "next-safe-action/hooks";
@@ -96,7 +93,7 @@ export function ProgramPartnersRejectedApplicationsPageClient() {
status: "rejected",
sortBy,
sortOrder,
- includeOnlinePresenceVerification: true,
+ includePartnerPlatformPropss: true,
},
{ exclude: ["partnerId"] },
)}`,
@@ -109,6 +106,21 @@ export function ProgramPartnersRejectedApplicationsPageClient() {
const { groups } = useGroups();
+ // Create a separate map for platform lookups by partner ID
+ const platformsMapByPartnerId = useMemo(() => {
+ const map = new Map<
+ string,
+ Record<PlatformType, PartnerPlatformProps | null>
+ >();
+
+ partners?.forEach((partner) => {
+ if (partner.platforms) {
+ map.set(partner.id, buildSocialPlatformLookup(partner.platforms));
+ }
+ });
+ return map;
+ }, [partners]);
+
const [detailsSheetState, setDetailsSheetState] = useState<
| { open: false; partnerId: string | null }
| { open: true; partnerId: string }
@@ -209,11 +221,13 @@ export function ProgramPartnersRejectedApplicationsPageClient() {
id: "website",
header: "Website",
minSize: 150,
- cell: ({ row }) => {
+ cell: ({ row }: { row: Row<EnrolledPartnerProps> }) => {
+ const platformsMap = platformsMapByPartnerId.get(row.original.id);
+
return (
<PartnerSocialColumn
- value={getDomainWithoutWWW(row.original.website) ?? "-"}
- verified={!!row.original.websiteVerifiedAt}
+ platform={platformsMap?.website}
+ platformName="website"
/>
);
},
@@ -222,12 +236,13 @@ export function ProgramPartnersRejectedApplicationsPageClient() {
id: "youtube",
header: "YouTube",
minSize: 150,
- cell: ({ row }) => {
+ cell: ({ row }: { row: Row<EnrolledPartnerProps> }) => {
+ const platformsMap = platformsMapByPartnerId.get(row.original.id);
+
return (
<PartnerSocialColumn
- at
- value={row.original.youtube}
- verified={!!row.original.youtubeVerifiedAt}
+ platform={platformsMap?.youtube}
+ platformName="youtube"
/>
);
},
@@ -236,12 +251,13 @@ export function ProgramPartnersRejectedApplicationsPageClient() {
id: "twitter",
header: "X/Twitter",
minSize: 150,
- cell: ({ row }) => {
+ cell: ({ row }: { row: Row<EnrolledPartnerProps> }) => {
+ const platformsMap = platformsMapByPartnerId.get(row.original.id);
+
return (
<PartnerSocialColumn
- at
- value={row.original.twitter}
- verified={!!row.original.twitterVerifiedAt}
+ platform={platformsMap?.twitter}
+ platformName="twitter"
/>
);
},
@@ -250,11 +266,13 @@ export function ProgramPartnersRejectedApplicationsPageClient() {
id: "linkedin",
header: "LinkedIn",
minSize: 150,
- cell: ({ row }) => {
+ cell: ({ row }: { row: Row<EnrolledPartnerProps> }) => {
+ const platformsMap = platformsMapByPartnerId.get(row.original.id);
+
return (
<PartnerSocialColumn
- value={row.original.linkedin}
- verified={!!row.original.linkedinVerifiedAt}
+ platform={platformsMap?.linkedin}
+ platformName="linkedin"
/>
);
},
@@ -263,12 +281,13 @@ export function ProgramPartnersRejectedApplicationsPageClient() {
id: "instagram",
header: "Instagram",
minSize: 150,
- cell: ({ row }) => {
+ cell: ({ row }: { row: Row<EnrolledPartnerProps> }) => {
+ const platformsMap = platformsMapByPartnerId.get(row.original.id);
+
return (
<PartnerSocialColumn
- at
- value={row.original.instagram}
- verified={!!row.original.instagramVerifiedAt}
+ platform={platformsMap?.instagram}
+ platformName="instagram"
/>
);
},
@@ -277,12 +296,13 @@ export function ProgramPartnersRejectedApplicationsPageClient() {
id: "tiktok",
header: "TikTok",
minSize: 150,
- cell: ({ row }) => {
+ cell: ({ row }: { row: Row<EnrolledPartnerProps> }) => {
+ const platformsMap = platformsMapByPartnerId.get(row.original.id);
+
return (
<PartnerSocialColumn
- at
- value={row.original.tiktok}
- verified={!!row.original.tiktokVerifiedAt}
+ platform={platformsMap?.tiktok}
+ platformName="tiktok"
/>
);
},
@@ -301,7 +321,7 @@ export function ProgramPartnersRejectedApplicationsPageClient() {
),
},
],
- [workspaceId, groups],
+ [workspaceId, groups, platformsMapByPartnerId],
);
const { table, ...tableProps } = useTable<EnrolledPartnerProps>({
diff --git a/apps/web/lib/actions/partners/online-presence-providers.ts b/apps/web/lib/actions/partners/online-presence-providers.ts
deleted file mode 100644
index 714ffd165d..0000000000
--- a/apps/web/lib/actions/partners/online-presence-providers.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-import { Partner } from "@dub/prisma/client";
-
-type OnlinePresenceProvider = {
- verifiedColumn: string;
- authUrl: string;
- tokenUrl: string;
- clientId: string | null;
- clientSecret: string | null;
- clientIdParam?: string;
- pkce?: boolean;
- scopes: string;
- verify: (props: { partner: Partner; accessToken: string }) => Promise<{
- verified: boolean;
- metadata?: Record<string, string>;
- }>;
-};
-
-export const ONLINE_PRESENCE_PROVIDERS: Record<string, OnlinePresenceProvider> =
- {
- youtube: {
- verifiedColumn: "youtubeVerifiedAt",
- authUrl: "https://accounts.google.com/o/oauth2/v2/auth",
- tokenUrl: "https://oauth2.googleapis.com/token",
- clientId: process.env.YOUTUBE_CLIENT_ID ?? null,
- clientSecret: process.env.YOUTUBE_CLIENT_SECRET ?? null,
- scopes: "https://www.googleapis.com/auth/youtube.readonly",
- verify: async ({ partner, accessToken }) => {
- if (!partner.youtube)
- return {
- verified: false,
- };
-
- // Fetch channel info
- const channelResponse = await fetch(
- "https://www.googleapis.com/youtube/v3/channels?part=snippet,statistics&mine=true",
- {
- headers: {
- Authorization: `Bearer ${accessToken}`,
- },
- },
- ).then((r) => r.json());
-
- const data = channelResponse?.items?.[0];
-
- if (!data) {
- return {
- verified: false,
- };
- }
-
- const channelId = data.id;
- const handle = data.snippet.customUrl;
- const { subscriberCount, videoCount, viewCount } = data.statistics;
-
- return {
- verified:
- !!handle &&
- `@${partner.youtube?.toLowerCase()}` === handle.toLowerCase(),
- metadata: {
- channelId,
- handle,
- subscriberCount,
- videoCount,
- viewCount,
- },
- };
- },
- },
- twitter: {
- verifiedColumn: "twitterVerifiedAt",
- authUrl: "https://x.com/i/oauth2/authorize",
- tokenUrl: "https://api.x.com/2/oauth2/token",
- clientId: process.env.TWITTER_CLIENT_ID ?? null,
- clientSecret: process.env.TWITTER_CLIENT_SECRET ?? null,
- pkce: true,
- scopes: "users.read tweet.read",
- verify: async ({ partner, accessToken }) => {
- if (!partner.twitter)
- return {
- verified: false,
- };
-
- // Fetch user info
- const userResponse = await fetch("https://api.twitter.com/2/users/me", {
- headers: {
- Authorization: `Bearer ${accessToken}`,
- },
- }).then((r) => r.json());
-
- const username = userResponse?.data?.username;
-
- return {
- verified:
- !!username &&
- partner.twitter.toLowerCase() === username.toLowerCase(),
- };
- },
- },
- tiktok: {
- verifiedColumn: "tiktokVerifiedAt",
- authUrl: "https://www.tiktok.com/v2/auth/authorize",
- tokenUrl: "https://open.tiktokapis.com/v2/oauth/token/",
- clientId: process.env.TIKTOK_CLIENT_ID ?? null,
- clientSecret: process.env.TIKTOK_CLIENT_SECRET ?? null,
- clientIdParam: "client_key",
- scopes: "user.info.basic,user.info.profile",
- verify: async ({ partner, accessToken }) => {
- if (!partner.tiktok)
- return {
- verified: false,
- };
-
- // Fetch user info
- const userResponse = await fetch(
- "https://open.tiktokapis.com/v2/user/info/?fields=username",
- {
- headers: {
- Authorization: `Bearer ${accessToken}`,
- },
- },
- ).then((r) => r.json());
-
- const username = userResponse?.data?.user?.username;
-
- return {
- verified:
- !!username &&
- partner.tiktok.toLowerCase() === username.toLowerCase(),
- };
- },
- },
- };
diff --git a/apps/web/lib/actions/partners/start-partner-platform-verification.ts b/apps/web/lib/actions/partners/start-partner-platform-verification.ts
new file mode 100644
index 0000000000..056da5761f
--- /dev/null
+++ b/apps/web/lib/actions/partners/start-partner-platform-verification.ts
@@ -0,0 +1,242 @@
+"use server";
+
+import {
+ generateCodeChallengeHash,
+ generateCodeVerifier,
+} from "@/lib/api/oauth/utils";
+import { ONLINE_PRESENCE_PROVIDERS } from "@/lib/api/partner-profile/online-presence-providers";
+import { upsertPartnerPlatform } from "@/lib/api/partner-profile/upsert-partner-platform";
+import { generateOTP } from "@/lib/auth/utils";
+import {
+ sanitizeSocialHandle,
+ SOCIAL_PLATFORM_CONFIGS,
+} from "@/lib/social-utils";
+import { ratelimit } from "@/lib/upstash/ratelimit";
+import { redis } from "@/lib/upstash/redis";
+import { PlatformType } from "@dub/prisma/client";
+import { nanoid, PARTNERS_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { cookies } from "next/headers";
+import { v4 as uuid } from "uuid";
+import { z } from "zod";
+import { authPartnerActionClient } from "../safe-action";
+
+const startPartnerPlatformVerificationSchema = z.object({
+ platform: z.enum(PlatformType),
+ handle: z.string().min(1).max(50),
+ source: z.enum(["onboarding", "settings"]).default("onboarding"),
+});
+
+type VerificationResult =
+ | { type: "oauth"; oauthUrl: string }
+ | { type: "verification_code"; verificationCode: string }
+ | { type: "txt_record"; websiteTxtRecord: string };
+
+type VerificationParams = {
+ partnerId: string;
+ platform: PlatformType;
+ handle: string;
+ source: "onboarding" | "settings";
+};
+
+/**
+ * Starts the social platform verification process for a partner.
+ * Supports three verification methods:
+ * - OAuth: For platforms like Twitter, TikTok, and LinkedIn (returns OAuth URL)
+ * - Verification Code: For platforms like YouTube and Instagram (returns code to display)
+ * - TXT Record: For website verification (returns DNS TXT record)
+ */
+export const startPartnerPlatformVerificationAction = authPartnerActionClient
+ .inputSchema(startPartnerPlatformVerificationSchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { partner } = ctx;
+ const { platform, handle, source } = parsedInput;
+
+ // Rate limit check
+ const { success } = await ratelimit(5, "1 h").limit(
+ `social-verification:${partner.id}:${platform}`,
+ );
+
+ if (!success) {
+ throw new Error(
+ "Too many verification attempts. Please try again later.",
+ );
+ }
+
+ const params: VerificationParams = {
+ partnerId: partner.id,
+ platform,
+ handle,
+ source,
+ };
+
+ // For website
+ if (platform === "website") {
+ return startWebsiteVerification(params);
+ }
+
+ // For OAuth based verification
+ const oauthProvider = ONLINE_PRESENCE_PROVIDERS[platform];
+ if (oauthProvider) {
+ return startOAuthVerification(params);
+ }
+
+ // For code based verification
+ return startCodeVerification(params);
+ });
+
+// Start website verification using TXT record
+async function startWebsiteVerification({
+ partnerId,
+ handle,
+}: Pick<VerificationParams, "partnerId" | "handle">): Promise<
+ Extract<VerificationResult, { type: "txt_record" }>
+> {
+ const websiteTxtRecord = `dub-domain-verification=${uuid()}`;
+
+ await upsertPartnerPlatform({
+ where: {
+ partnerId,
+ type: "website",
+ },
+ data: {
+ identifier: handle,
+ verifiedAt: null,
+ metadata: {
+ websiteTxtRecord,
+ },
+ },
+ });
+
+ return {
+ type: "txt_record",
+ websiteTxtRecord,
+ };
+}
+
+// Start OAuth verification for platforms Twitter, TikTok and LinkedIn
+async function startOAuthVerification({
+ partnerId,
+ platform,
+ handle: rawHandle,
+ source,
+}: VerificationParams): Promise<
+ Extract<VerificationResult, { type: "oauth" }>
+> {
+ const oauthProvider = ONLINE_PRESENCE_PROVIDERS[platform];
+ if (!oauthProvider || !oauthProvider.clientId) {
+ throw new Error(`OAuth provider not configured for ${platform}`);
+ }
+
+ const platformConfig = SOCIAL_PLATFORM_CONFIGS[platform];
+
+ if (!platformConfig) {
+ throw new Error(`Invalid platform: ${platform}`);
+ }
+
+ const handle = sanitizeSocialHandle(rawHandle, platform);
+
+ if (!handle) {
+ throw new Error(`Please enter a valid handle for ${platformConfig.name}.`);
+ }
+
+ // Store handle before OAuth redirect
+ await upsertPartnerPlatform({
+ where: {
+ partnerId,
+ type: platform,
+ },
+ data: {
+ identifier: handle,
+ verifiedAt: null,
+ },
+ });
+
+ // Generate OAuth authorization URL
+ const state = nanoid(16);
+ await redis.set(
+ `partnerSocialVerification:${state}`,
+ {
+ platform,
+ partnerId,
+ source,
+ },
+ {
+ ex: 5 * 60, // 5 minutes
+ },
+ );
+
+ const searchParams = new URLSearchParams({
+ [oauthProvider.clientIdParam ?? "client_id"]: oauthProvider.clientId,
+ redirect_uri: `${PARTNERS_DOMAIN_WITH_NGROK}/api/partners/online-presence/callback`,
+ scope: oauthProvider.scopes,
+ response_type: "code",
+ state,
+ });
+
+ // Handle PKCE for platforms that require it (e.g., Twitter)
+ if (oauthProvider.pkce) {
+ const codeVerifier = generateCodeVerifier();
+ const codeChallenge = await generateCodeChallengeHash(codeVerifier);
+
+ // Store code verifier in cookie for callback
+ (await cookies()).set("online_presence_code_verifier", codeVerifier, {
+ httpOnly: true,
+ secure: process.env.NODE_ENV === "production",
+ sameSite: "lax",
+ maxAge: 60 * 5, // 5 minutes
+ });
+
+ searchParams.set("code_challenge", codeChallenge);
+ searchParams.set("code_challenge_method", "S256");
+ }
+
+ const oauthUrl = `${oauthProvider.authUrl}?${searchParams.toString()}`;
+
+ return {
+ type: "oauth",
+ oauthUrl,
+ };
+}
+
+// Start verification code flow for platforms like YouTube, Instagram
+async function startCodeVerification({
+ partnerId,
+ platform,
+ handle: rawHandle,
+}: Pick<VerificationParams, "partnerId" | "platform" | "handle">): Promise<
+ Extract<VerificationResult, { type: "verification_code" }>
+> {
+ const platformConfig = SOCIAL_PLATFORM_CONFIGS[platform];
+
+ if (!platformConfig) {
+ throw new Error(`Invalid platform: ${platform}`);
+ }
+
+ const handle = sanitizeSocialHandle(rawHandle, platform);
+
+ if (!handle) {
+ throw new Error(`Please enter a valid handle for ${platformConfig.name}.`);
+ }
+
+ const verificationCode = generateOTP();
+ const cacheKey = `social-verification:${partnerId}:${platform}:${handle}`;
+ await redis.set(cacheKey, verificationCode, {
+ ex: 60 * 60 * 24, // 24 hours
+ });
+
+ await upsertPartnerPlatform({
+ where: {
+ partnerId,
+ type: platform,
+ },
+ data: {
+ identifier: handle,
+ verifiedAt: null,
+ },
+ });
+
+ return {
+ type: "verification_code",
+ verificationCode,
+ };
+}
diff --git a/apps/web/lib/actions/partners/update-online-presence.ts b/apps/web/lib/actions/partners/update-online-presence.ts
index 387a9389e8..b91b54a14e 100644
--- a/apps/web/lib/actions/partners/update-online-presence.ts
+++ b/apps/web/lib/actions/partners/update-online-presence.ts
@@ -1,196 +1,191 @@
"use server";
-import {
- generateCodeChallengeHash,
- generateCodeVerifier,
-} from "@/lib/api/oauth/utils";
+import { upsertPartnerPlatform } from "@/lib/api/partner-profile/upsert-partner-platform";
import { sanitizeSocialHandle, sanitizeWebsite } from "@/lib/social-utils";
import { parseUrlSchemaAllowEmpty } from "@/lib/zod/schemas/utils";
import { prisma } from "@dub/prisma";
-import { isValidUrl, PARTNERS_DOMAIN_WITH_NGROK } from "@dub/utils";
-import { cookies } from "next/headers";
-import { v4 as uuid } from "uuid";
+import { PartnerPlatform, PlatformType } from "@dub/prisma/client";
+import { isValidUrl } from "@dub/utils";
import * as z from "zod/v4";
import { authPartnerActionClient } from "../safe-action";
-import { ONLINE_PRESENCE_PROVIDERS } from "./online-presence-providers";
-const updateOnlinePresenceSchema = z.object({
- website: parseUrlSchemaAllowEmpty()
- .nullish()
- .transform((input) =>
- input === undefined ? undefined : sanitizeWebsite(input),
- ),
- youtube: z
- .string()
- .nullish()
- .transform((input) =>
- input === undefined ? undefined : sanitizeSocialHandle(input, "youtube"),
- ),
- twitter: z
- .string()
- .nullish()
- .transform((input) =>
- input === undefined ? undefined : sanitizeSocialHandle(input, "twitter"),
- ),
- linkedin: z
+/**
+ * Helper function to create a schema for social platform handles.
+ * Preserves undefined (ignore) and null (remove), sanitizes string values.
+ */
+const createSocialPlatformSchema = (platform: PlatformType) => {
+ return z
.string()
.nullish()
- .transform((input) =>
- input === undefined ? undefined : sanitizeSocialHandle(input, "linkedin"),
- ),
- instagram: z
- .string()
- .nullish()
- .transform((input) =>
- input === undefined
- ? undefined
- : sanitizeSocialHandle(input, "instagram"),
- ),
- tiktok: z
- .string()
- .nullish()
- .transform((input) =>
- input === undefined ? undefined : sanitizeSocialHandle(input, "tiktok"),
- ),
- source: z.enum(["onboarding", "settings"]).default("onboarding"),
-});
-
-const updateOnlinePresenceResponseSchema = updateOnlinePresenceSchema.extend({
- websiteTxtRecord: z.string().nullable(),
- verificationUrls: z.record(z.string(), z.url()),
-});
+ .transform((input) => {
+ if (input === undefined) return undefined;
+ if (input === null) return null;
+ return sanitizeSocialHandle(input, platform);
+ });
+};
-export const updateOnlinePresenceAction = authPartnerActionClient
- .inputSchema(
- updateOnlinePresenceSchema.refine(
- async (data) => {
- return !data.website || isValidUrl(data.website);
+/**
+ * Helper function to create a schema for website URLs.
+ * Preserves undefined (ignore) and null (remove), sanitizes string values.
+ */
+const createWebsiteSchema = () => {
+ return parseUrlSchemaAllowEmpty()
+ .nullish()
+ .transform((input) => {
+ if (input === undefined) return undefined;
+ if (input === null) return null;
+ return sanitizeWebsite(input);
+ })
+ .refine(
+ (value) => {
+ return !value || isValidUrl(value);
},
{
message: "Invalid website URL.",
},
- ),
- )
+ );
+};
+
+const updateOnlinePresenceSchema = z.object({
+ website: createWebsiteSchema(),
+ youtube: createSocialPlatformSchema("youtube"),
+ twitter: createSocialPlatformSchema("twitter"),
+ linkedin: createSocialPlatformSchema("linkedin"),
+ instagram: createSocialPlatformSchema("instagram"),
+ tiktok: createSocialPlatformSchema("tiktok"),
+ source: z.enum(["onboarding", "settings"]).default("onboarding"),
+});
+
+export const updateOnlinePresenceAction = authPartnerActionClient
+ .inputSchema(updateOnlinePresenceSchema)
.action(async ({ ctx, parsedInput }) => {
const { partner } = ctx;
- let domainChanged = false;
-
- try {
- let oldDomain = partner.website
- ? new URL(partner.website).hostname
- : null;
- let newDomain = parsedInput.website
- ? new URL(parsedInput.website).hostname
- : null;
- domainChanged = oldDomain !== newDomain;
- } catch (e) {
- console.error(
- "Failed to get domain from partner website",
- { old: partner.website, new: parsedInput.website },
- e,
- );
- domainChanged = true;
- }
-
- const updateData = {
- ...(parsedInput.website !== undefined && {
- website: parsedInput.website,
- ...(domainChanged && {
- websiteVerifiedAt: null,
- websiteTxtRecord: `dub-domain-verification=${uuid()}`,
- }),
- }),
- ...(parsedInput.youtube !== undefined && {
- youtube: parsedInput.youtube,
- youtubeVerifiedAt:
- parsedInput.youtube !== partner.youtube ? null : undefined,
- }),
- ...(parsedInput.twitter !== undefined && {
- twitter: parsedInput.twitter,
- twitterVerifiedAt:
- parsedInput.twitter !== partner.twitter ? null : undefined,
- }),
- ...(parsedInput.linkedin !== undefined && {
- linkedin: parsedInput.linkedin,
- linkedinVerifiedAt:
- parsedInput.linkedin !== partner.linkedin ? null : undefined,
- }),
- ...(parsedInput.instagram !== undefined && {
- instagram: parsedInput.instagram,
- instagramVerifiedAt:
- parsedInput.instagram !== partner.instagram ? null : undefined,
- }),
- ...(parsedInput.tiktok !== undefined && {
- tiktok: parsedInput.tiktok,
- tiktokVerifiedAt:
- parsedInput.tiktok !== partner.tiktok ? null : undefined,
- }),
- };
-
- const updatedPartner = await prisma.partner.update({
+ const partnerPlatform = await prisma.partnerPlatform.findMany({
where: {
- id: partner.id,
+ partnerId: partner.id,
},
- data: updateData,
});
- return {
- success: true,
- ...updateOnlinePresenceResponseSchema.parse({
- ...updatedPartner,
- verificationUrls: Object.fromEntries(
- await Promise.all(
- Object.entries(ONLINE_PRESENCE_PROVIDERS)
- .filter(
- ([key, data]) =>
- updatedPartner[key] && !updatedPartner[data.verifiedColumn],
- )
- .map(async ([key, data]) => {
- if (!data.clientId) return [key, null];
-
- const params: Record<string, string> = {
- [data.clientIdParam ?? "client_id"]: data.clientId,
- redirect_uri: `${PARTNERS_DOMAIN_WITH_NGROK}/api/partners/online-presence/callback`,
- scope: data.scopes,
- response_type: "code",
- state: Buffer.from(
- JSON.stringify({
- provider: key,
- partnerId: partner.id,
- source: parsedInput.source,
- }),
- ).toString("base64"),
- };
-
- if (data.pkce) {
- const codeVerifier = generateCodeVerifier();
- const codeChallenge =
- await generateCodeChallengeHash(codeVerifier);
-
- // Store code verifier in cookie
- (await cookies()).set(
- "online_presence_code_verifier",
- codeVerifier,
- {
- httpOnly: true,
- secure: process.env.NODE_ENV === "production",
- sameSite: "lax",
- maxAge: 60 * 5, // 5 minutes
- },
- );
-
- params.code_challenge = codeChallenge;
- params.code_challenge_method = "S256";
- }
-
- return [
- key,
- `${data.authUrl}?${new URLSearchParams(params).toString()}`,
- ];
- }),
- ),
+ const platformIdentifiers = new Map(
+ partnerPlatform.map((p) => [p.type, p.identifier]),
+ );
+
+ const partnerPlatformsData: Pick<
+ PartnerPlatform,
+ "type" | "identifier" | "verifiedAt"
+ >[] = [];
+
+ const platformsToDelete: Array<{
+ partnerId: string;
+ type: PlatformType;
+ }> = [];
+
+ // Define platform configurations
+ // null = remove, undefined = ignore (no changes)
+ const platformConfigs: Array<{
+ platform: PlatformType;
+ inputValue: string | null | undefined;
+ }> = [
+ { platform: "youtube", inputValue: parsedInput.youtube },
+ { platform: "twitter", inputValue: parsedInput.twitter },
+ { platform: "linkedin", inputValue: parsedInput.linkedin },
+ { platform: "instagram", inputValue: parsedInput.instagram },
+ { platform: "tiktok", inputValue: parsedInput.tiktok },
+ { platform: "website", inputValue: parsedInput.website },
+ ];
+
+ for (const { platform, inputValue } of platformConfigs) {
+ const currentIdentifier = platformIdentifiers.get(platform);
+
+ // Handle deletion: null = remove
+ if (inputValue === null && currentIdentifier !== undefined) {
+ platformsToDelete.push({
+ partnerId: partner.id,
+ type: platform,
+ });
+ continue;
+ }
+
+ // Handle update: non-null, non-undefined value that differs from current
+ if (
+ inputValue !== undefined &&
+ inputValue !== null &&
+ inputValue !== currentIdentifier
+ ) {
+ // Special handling for website: check domain change
+ if (platform === "website") {
+ let domainChanged = false;
+
+ try {
+ const oldDomain = currentIdentifier
+ ? new URL(currentIdentifier).hostname
+ : null;
+ const newDomain = inputValue ? new URL(inputValue).hostname : null;
+
+ domainChanged =
+ oldDomain?.toLowerCase() !== newDomain?.toLowerCase();
+ } catch (error) {
+ console.error("Failed to get domain from partner website", error);
+ domainChanged = true;
+ }
+
+ if (domainChanged) {
+ partnerPlatformsData.push({
+ type: "website",
+ identifier: inputValue,
+ verifiedAt: null,
+ });
+ }
+ } else {
+ // For all other platforms, update if value changed
+ partnerPlatformsData.push({
+ type: platform,
+ identifier: inputValue,
+ verifiedAt: null,
+ });
+ }
+ }
+ }
+
+ // Execute deletions and updates in parallel
+ const operations: Promise<unknown>[] = [];
+
+ if (platformsToDelete.length > 0) {
+ operations.push(
+ ...platformsToDelete.map(({ partnerId, type }) =>
+ prisma.partnerPlatform.delete({
+ where: {
+ partnerId_type: {
+ partnerId,
+ type,
+ },
+ },
+ }),
+ ),
+ );
+ }
+
+ if (partnerPlatformsData.length > 0) {
+ operations.push(
+ ...partnerPlatformsData.map((item) =>
+ upsertPartnerPlatform({
+ where: {
+ partnerId: partner.id,
+ type: item.type,
+ },
+ data: {
+ identifier: item.identifier,
+ verifiedAt: item.verifiedAt,
+ },
+ }),
),
- }),
- };
+ );
+ }
+
+ if (operations.length === 0) {
+ return;
+ }
+
+ await Promise.all(operations);
});
diff --git a/apps/web/lib/actions/partners/update-partner-profile.ts b/apps/web/lib/actions/partners/update-partner-profile.ts
index 92f3fe3032..609371bf55 100644
--- a/apps/web/lib/actions/partners/update-partner-profile.ts
+++ b/apps/web/lib/actions/partners/update-partner-profile.ts
@@ -142,6 +142,7 @@ export const updatePartnerProfileAction = authPartnerActionClient
preferredEarningStructures: true,
salesChannels: true,
programs: true,
+ platforms: true,
},
});
diff --git a/apps/web/lib/actions/partners/verify-domain.ts b/apps/web/lib/actions/partners/verify-domain.ts
index 2fb91f52e0..673f1314f8 100644
--- a/apps/web/lib/actions/partners/verify-domain.ts
+++ b/apps/web/lib/actions/partners/verify-domain.ts
@@ -8,47 +8,67 @@ export const verifyDomainAction = authPartnerActionClient.action(
async ({ ctx }) => {
const { partner } = ctx;
- if (!partner.website || !partner.websiteTxtRecord)
+ const partnerPlatform = await prisma.partnerPlatform.findUnique({
+ where: {
+ partnerId_type: {
+ partnerId: partner.id,
+ type: "website",
+ },
+ },
+ });
+
+ if (!partnerPlatform || !partnerPlatform.identifier) {
+ throw new Error(
+ "Website not found on your partner profile. Please restart the verification process.",
+ );
+ }
+
+ const metadata = partnerPlatform.metadata as { websiteTxtRecord: string };
+
+ if (!metadata || !metadata.websiteTxtRecord) {
throw new Error(
- "Failed to verify domain: website or websiteTxtRecord is not set",
+ "Website verification data not found. Please restart the verification process.",
);
+ }
let domain: string | null = null;
try {
- domain = new URL(partner.website).hostname;
+ domain = new URL(partnerPlatform.identifier).hostname;
} catch (e) {
- throw new Error("Failed to get domain from website");
+ throw new Error("Please make sure the website is a valid URL.");
}
const valid = await new Promise((resolve, reject) =>
dns.resolveTxt(domain, (err, addresses) => {
- if (err) reject(err);
- else
+ if (err) {
+ reject(err);
+ } else {
resolve(
- addresses.some(
- (address) =>
- partner.websiteTxtRecord &&
- address.includes(partner.websiteTxtRecord),
+ addresses.some((address) =>
+ address.includes(metadata.websiteTxtRecord),
),
);
+ }
}),
);
- if (!valid) throw new Error("TXT record not found");
+ if (!valid) {
+ throw new Error(
+ "TXT record not found. Please make sure the TXT record is set correctly and try again.",
+ );
+ }
- await prisma.partner.update({
+ await prisma.partnerPlatform.update({
where: {
- id: partner.id,
+ partnerId_type: {
+ partnerId: partner.id,
+ type: "website",
+ },
},
data: {
- websiteVerifiedAt: new Date(),
+ verifiedAt: new Date(),
},
});
-
- return {
- success: true,
- websiteVerifiedAt: new Date(),
- };
},
);
diff --git a/apps/web/lib/actions/partners/verify-social-account-by-code.ts b/apps/web/lib/actions/partners/verify-social-account-by-code.ts
new file mode 100644
index 0000000000..933e2b285d
--- /dev/null
+++ b/apps/web/lib/actions/partners/verify-social-account-by-code.ts
@@ -0,0 +1,121 @@
+"use server";
+
+import { scrapeCreatorsClient } from "@/lib/api/scrapecreators/client";
+import { ratelimit } from "@/lib/upstash";
+import { redis } from "@/lib/upstash/redis";
+import { prisma } from "@dub/prisma";
+import { PlatformType } from "@dub/prisma/client";
+import { z } from "zod";
+import { authPartnerActionClient } from "../safe-action";
+
+const schema = z.object({
+ platform: z.enum(PlatformType),
+ handle: z.string().min(1),
+});
+
+// Verify social accounts using the verification code
+export const verifySocialAccountByCodeAction = authPartnerActionClient
+ .inputSchema(schema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { partner } = ctx;
+ const { platform, handle } = parsedInput;
+
+ if (!["youtube", "instagram"].includes(platform)) {
+ throw new Error("Only YouTube and Instagram are supported.");
+ }
+
+ // Rate limit check
+ const { success } = await ratelimit(5, "1 h").limit(
+ `social-verification:${partner.id}:${platform}`,
+ );
+
+ if (!success) {
+ throw new Error(
+ "Too many verification attempts. Please try again later.",
+ );
+ }
+
+ // Get the verification code from Redis
+ const cacheKey = `social-verification:${partner.id}:${platform}:${handle}`;
+ const verificationCode = await redis.get<string>(cacheKey);
+
+ if (!verificationCode) {
+ throw new Error(
+ "Verification code not found or expired. Please start verification again.",
+ );
+ }
+
+ // Check if the account is already verified
+ const partnerPlatform = await prisma.partnerPlatform.findUnique({
+ where: {
+ partnerId_type: {
+ partnerId: partner.id,
+ type: platform,
+ },
+ },
+ select: {
+ identifier: true,
+ verifiedAt: true,
+ },
+ });
+
+ if (!partnerPlatform) {
+ throw new Error("Social account not found. Please restart verification.");
+ }
+
+ // No further action is needed if the account is already verified
+ if (
+ partnerPlatform?.identifier?.toLowerCase() === handle.toLowerCase() &&
+ partnerPlatform.verifiedAt
+ ) {
+ return;
+ }
+
+ // Verifies that a verification code exists in the account's profile bio/description.
+ // Fetches the account profile and checks if the provided code appears in any of the
+ // profile text fields (description, about, bio, summary).
+ const socialProfile = await scrapeCreatorsClient.fetchSocialProfile({
+ platform,
+ handle,
+ });
+
+ if (!socialProfile) {
+ throw new Error(
+ "We were unable to retrieve your social media profile. Please try again.",
+ );
+ }
+
+ if (!socialProfile.description) {
+ throw new Error(
+ `We could not find a public ${
+ platform === "youtube" ? "channel description" : "bio"
+ } for this account. Please ensure it is visible and try again.`,
+ );
+ }
+
+ const isValid = socialProfile.description.includes(verificationCode);
+
+ if (!isValid) {
+ throw new Error(
+ `The verification code was not found in your ${
+ platform === "youtube" ? "channel description" : "bio"
+ }. Please add the code exactly as provided, save your changes, and try again.`,
+ );
+ }
+
+ await prisma.partnerPlatform.update({
+ where: {
+ partnerId_type: {
+ partnerId: partner.id,
+ type: platform,
+ },
+ },
+ data: {
+ verifiedAt: new Date(),
+ platformId: socialProfile.platformId,
+ },
+ });
+
+ // Delete the verification code from Redis
+ await redis.del(cacheKey);
+ });
diff --git a/apps/web/lib/api/fraud/get-partner-application-risks.ts b/apps/web/lib/api/fraud/get-partner-application-risks.ts
index f81c463226..2108f352d8 100644
--- a/apps/web/lib/api/fraud/get-partner-application-risks.ts
+++ b/apps/web/lib/api/fraud/get-partner-application-risks.ts
@@ -1,7 +1,7 @@
import { getHighestSeverity } from "@/lib/get-highest-severity";
-import { ExtendedFraudRuleType } from "@/lib/types";
+import { ExtendedFraudRuleType, PartnerProps } from "@/lib/types";
import { prisma } from "@dub/prisma";
-import { Partner, Program } from "@dub/prisma/client";
+import { Program } from "@dub/prisma/client";
import { FRAUD_RULES } from "./constants";
import { checkPartnerEmailDomainMismatch } from "./rules/check-partner-email-domain-mismatch";
import { checkPartnerEmailMasked } from "./rules/check-partner-email-masked";
@@ -13,19 +13,7 @@ export async function getPartnerApplicationRisks({
partner,
}: {
program: Pick<Program, "id">;
- partner: Pick<
- Partner,
- | "id"
- | "email"
- | "website"
- | "websiteVerifiedAt"
- | "youtubeVerifiedAt"
- | "twitterVerifiedAt"
- | "linkedinVerifiedAt"
- | "instagramVerifiedAt"
- | "tiktokVerifiedAt"
- | "country"
- >;
+ partner: Pick<PartnerProps, "id" | "email" | "country" | "platforms">;
}) {
const fraudGroups = await prisma.fraudEventGroup.findMany({
where: {
diff --git a/apps/web/lib/api/fraud/rules/check-partner-email-domain-mismatch.ts b/apps/web/lib/api/fraud/rules/check-partner-email-domain-mismatch.ts
index ecd5559e6e..ea152ca3cf 100644
--- a/apps/web/lib/api/fraud/rules/check-partner-email-domain-mismatch.ts
+++ b/apps/web/lib/api/fraud/rules/check-partner-email-domain-mismatch.ts
@@ -1,4 +1,4 @@
-import { EnrolledPartnerExtendedProps } from "@/lib/types";
+import { PartnerProps } from "@/lib/types";
function normalizeDomain(domain: string) {
return domain
@@ -9,9 +9,15 @@ function normalizeDomain(domain: string) {
// Checks if the partner's email domain doesn't match their website domain
export function checkPartnerEmailDomainMismatch(
- partner: Pick<EnrolledPartnerExtendedProps, "email" | "website">,
+ partner: Pick<PartnerProps, "email" | "platforms">,
) {
- if (!partner.email || !partner.website) {
+ if (!partner.email || partner.platforms.length === 0) {
+ return false;
+ }
+
+ const website = partner.platforms.find((p) => p.type === "website");
+
+ if (!website || !website.identifier) {
return false;
}
@@ -24,7 +30,7 @@ export function checkPartnerEmailDomainMismatch(
let websiteDomain: string;
try {
- const websiteUrl = new URL(partner.website);
+ const websiteUrl = new URL(website.identifier);
websiteDomain = normalizeDomain(websiteUrl.hostname);
} catch (error) {
return false;
diff --git a/apps/web/lib/api/fraud/rules/check-partner-email-masked.ts b/apps/web/lib/api/fraud/rules/check-partner-email-masked.ts
index 2b46056b07..17156e5831 100644
--- a/apps/web/lib/api/fraud/rules/check-partner-email-masked.ts
+++ b/apps/web/lib/api/fraud/rules/check-partner-email-masked.ts
@@ -1,9 +1,7 @@
-import { EnrolledPartnerExtendedProps } from "@/lib/types";
+import { PartnerProps } from "@/lib/types";
// Checks if the partner is using an Apple private relay email address
-export function checkPartnerEmailMasked(
- partner: Pick<EnrolledPartnerExtendedProps, "email">,
-) {
+export function checkPartnerEmailMasked(partner: Pick<PartnerProps, "email">) {
if (!partner.email) {
return false;
}
diff --git a/apps/web/lib/api/fraud/rules/check-partner-no-social-links.ts b/apps/web/lib/api/fraud/rules/check-partner-no-social-links.ts
index 8f50ff5a7d..077b164c9c 100644
--- a/apps/web/lib/api/fraud/rules/check-partner-no-social-links.ts
+++ b/apps/web/lib/api/fraud/rules/check-partner-no-social-links.ts
@@ -1,20 +1,10 @@
-import { EnrolledPartnerExtendedProps } from "@/lib/types";
+import { PartnerProps } from "@/lib/types";
// Checks if the partner has neither a website nor any social media links
export function checkPartnerNoSocialLinks(
- partner: Pick<
- EnrolledPartnerExtendedProps,
- "website" | "youtube" | "twitter" | "linkedin" | "instagram" | "tiktok"
- >,
+ partner: Pick<PartnerProps, "platforms">,
) {
- const hasWebsite = partner.website && partner.website.trim().length > 0;
-
- const hasSocialLinks =
- (partner.youtube && partner.youtube.trim().length > 0) ||
- (partner.twitter && partner.twitter.trim().length > 0) ||
- (partner.linkedin && partner.linkedin.trim().length > 0) ||
- (partner.instagram && partner.instagram.trim().length > 0) ||
- (partner.tiktok && partner.tiktok.trim().length > 0);
-
- return !hasWebsite && !hasSocialLinks;
+ return !partner.platforms.some(
+ (p) => typeof p.identifier === "string" && p.identifier.trim().length > 0,
+ );
}
diff --git a/apps/web/lib/api/fraud/rules/check-partner-no-verified-social-links.ts b/apps/web/lib/api/fraud/rules/check-partner-no-verified-social-links.ts
index e1903c0fa5..e3cc388be1 100644
--- a/apps/web/lib/api/fraud/rules/check-partner-no-verified-social-links.ts
+++ b/apps/web/lib/api/fraud/rules/check-partner-no-verified-social-links.ts
@@ -1,25 +1,8 @@
-import { EnrolledPartnerExtendedProps } from "@/lib/types";
+import { PartnerProps } from "@/lib/types";
// Checks if the partner has no verified website or social media links
export function checkPartnerNoVerifiedSocialLinks(
- partner: Pick<
- EnrolledPartnerExtendedProps,
- | "websiteVerifiedAt"
- | "youtubeVerifiedAt"
- | "twitterVerifiedAt"
- | "linkedinVerifiedAt"
- | "instagramVerifiedAt"
- | "tiktokVerifiedAt"
- >,
+ partner: Pick<PartnerProps, "platforms">,
) {
- const hasVerifiedWebsite = partner.websiteVerifiedAt != null;
-
- const hasVerifiedSocialLinks =
- partner.youtubeVerifiedAt != null ||
- partner.twitterVerifiedAt != null ||
- partner.linkedinVerifiedAt != null ||
- partner.instagramVerifiedAt != null ||
- partner.tiktokVerifiedAt != null;
-
- return !hasVerifiedWebsite && !hasVerifiedSocialLinks;
+ return !partner.platforms.some((p) => p.verifiedAt != null);
}
diff --git a/apps/web/lib/api/network/calculate-partner-ranking.ts b/apps/web/lib/api/network/calculate-partner-ranking.ts
index 8eac083538..43c8252aec 100644
--- a/apps/web/lib/api/network/calculate-partner-ranking.ts
+++ b/apps/web/lib/api/network/calculate-partner-ranking.ts
@@ -90,13 +90,10 @@ export async function calculatePartnerRanking({
const whereClause = Prisma.join(conditions, " AND ");
// Rank partners with no online presence lower
- const hasProfileCheck = Prisma.sql`(
- p.website IS NOT NULL OR
- p.youtube IS NOT NULL OR
- p.twitter IS NOT NULL OR
- p.linkedin IS NOT NULL OR
- p.instagram IS NOT NULL OR
- p.tiktok IS NOT NULL
+ const hasProfileCheck = Prisma.sql`EXISTS (
+ SELECT 1
+ FROM PartnerPlatform pp
+ WHERE pp.partnerId = p.id
)`;
const orderByClause =
diff --git a/apps/web/lib/api/partner-profile/get-partner-for-program.ts b/apps/web/lib/api/partner-profile/get-partner-for-program.ts
index ca55837d38..7b1fdfad4d 100644
--- a/apps/web/lib/api/partner-profile/get-partner-for-program.ts
+++ b/apps/web/lib/api/partner-profile/get-partner-for-program.ts
@@ -20,6 +20,7 @@ export async function getPartnerForProgram({
industryInterests: true,
preferredEarningStructures: true,
salesChannels: true,
+ platforms: true,
},
},
links: true,
diff --git a/apps/web/lib/api/partner-profile/online-presence-providers.ts b/apps/web/lib/api/partner-profile/online-presence-providers.ts
new file mode 100644
index 0000000000..33e1d5b34f
--- /dev/null
+++ b/apps/web/lib/api/partner-profile/online-presence-providers.ts
@@ -0,0 +1,158 @@
+type OnlinePresenceProvider = {
+ authUrl: string;
+ tokenUrl: string;
+ clientId: string | null;
+ clientSecret: string | null;
+ clientIdParam?: string;
+ pkce?: boolean;
+ scopes: string;
+ verify: (props: { handle: string; accessToken: string }) => Promise<{
+ verified: boolean;
+ metadata?: Record<string, string>;
+ }>;
+};
+
+export const ONLINE_PRESENCE_PROVIDERS: Record<string, OnlinePresenceProvider> =
+ {
+ twitter: {
+ authUrl: "https://x.com/i/oauth2/authorize",
+ tokenUrl: "https://api.x.com/2/oauth2/token",
+ clientId: process.env.TWITTER_CLIENT_ID ?? null,
+ clientSecret: process.env.TWITTER_CLIENT_SECRET ?? null,
+ pkce: true,
+ scopes: "users.read tweet.read",
+ verify: async ({ handle, accessToken }) => {
+ if (!handle) {
+ return {
+ verified: false,
+ };
+ }
+
+ // Fetch user info
+ const response = await fetch("https://api.twitter.com/2/users/me", {
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ },
+ });
+
+ const userResponse = await response.json();
+
+ if (!response.ok) {
+ console.error("Failed to verify Twitter handle", userResponse);
+
+ return {
+ verified: false,
+ };
+ }
+
+ const username = userResponse?.data?.username;
+
+ if (!username) {
+ console.error(
+ "No username found in Twitter user response",
+ userResponse,
+ );
+
+ return {
+ verified: false,
+ };
+ }
+
+ return {
+ verified: handle.toLowerCase() === username.toLowerCase(),
+ };
+ },
+ },
+
+ tiktok: {
+ authUrl: "https://www.tiktok.com/v2/auth/authorize",
+ tokenUrl: "https://open.tiktokapis.com/v2/oauth/token/",
+ clientId: process.env.TIKTOK_CLIENT_ID ?? null,
+ clientSecret: process.env.TIKTOK_CLIENT_SECRET ?? null,
+ clientIdParam: "client_key",
+ scopes: "user.info.basic,user.info.profile",
+ verify: async ({ handle, accessToken }) => {
+ if (!handle) {
+ return {
+ verified: false,
+ };
+ }
+
+ // Fetch user info
+ const response = await fetch(
+ "https://open.tiktokapis.com/v2/user/info/?fields=username",
+ {
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ },
+ },
+ );
+
+ const userResponse = await response.json();
+
+ if (!response.ok) {
+ console.error("Failed to verify TikTok handle", userResponse);
+
+ return {
+ verified: false,
+ };
+ }
+
+ const username = userResponse?.data?.user?.username;
+
+ if (!username) {
+ console.error(
+ "No username found in TikTok user response",
+ userResponse,
+ );
+
+ return {
+ verified: false,
+ };
+ }
+
+ return {
+ verified: handle.toLowerCase() === username.toLowerCase(),
+ };
+ },
+ },
+
+ linkedin: {
+ authUrl: "https://www.linkedin.com/oauth/v2/authorization",
+ tokenUrl: "https://www.linkedin.com/oauth/v2/accessToken",
+ clientId: process.env.LINKEDIN_CLIENT_ID ?? null,
+ clientSecret: process.env.LINKEDIN_CLIENT_SECRET ?? null,
+ scopes: "openid profile",
+ verify: async ({ handle, accessToken }) => {
+ if (!handle) {
+ return {
+ verified: false,
+ };
+ }
+
+ // Fetch user info using OpenID Connect userinfo endpoint
+ const response = await fetch("https://api.linkedin.com/v2/userinfo", {
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ },
+ });
+
+ const userResponse = await response.json();
+
+ if (!response.ok) {
+ console.error("Failed to verify LinkedIn handle", userResponse);
+
+ return {
+ verified: false,
+ };
+ }
+
+ // TODO:
+ // We can't verify the handle because the LinkedIn API doesn't return the vanity name in the response
+
+ return {
+ verified: false,
+ };
+ },
+ },
+ };
diff --git a/apps/web/lib/api/partner-profile/upsert-partner-platform.ts b/apps/web/lib/api/partner-profile/upsert-partner-platform.ts
new file mode 100644
index 0000000000..ad1a4d1131
--- /dev/null
+++ b/apps/web/lib/api/partner-profile/upsert-partner-platform.ts
@@ -0,0 +1,41 @@
+import { prisma } from "@dub/prisma";
+import { PlatformType, Prisma } from "@dub/prisma/client";
+
+type UpsertPartnerPlatformParams = {
+ where: {
+ partnerId: string;
+ type: PlatformType;
+ };
+ data: Pick<
+ Prisma.PartnerPlatformCreateInput,
+ "identifier" | "verifiedAt" | "metadata"
+ >;
+};
+
+export async function upsertPartnerPlatform({
+ where,
+ data,
+}: UpsertPartnerPlatformParams) {
+ const { partnerId, type } = where;
+
+ return await prisma.partnerPlatform.upsert({
+ where: {
+ partnerId_type: {
+ partnerId,
+ type,
+ },
+ },
+ create: {
+ partnerId,
+ type,
+ identifier: data.identifier,
+ verifiedAt: data.verifiedAt,
+ metadata: data.metadata,
+ },
+ update: {
+ identifier: data.identifier,
+ verifiedAt: data.verifiedAt,
+ metadata: data.metadata,
+ },
+ });
+}
diff --git a/apps/web/lib/api/partners/create-and-enroll-partner.ts b/apps/web/lib/api/partners/create-and-enroll-partner.ts
index 86d3fc6cbf..30983dec8d 100644
--- a/apps/web/lib/api/partners/create-and-enroll-partner.ts
+++ b/apps/web/lib/api/partners/create-and-enroll-partner.ts
@@ -1,6 +1,7 @@
"use server";
import { createId } from "@/lib/api/create-id";
+import { polyfillSocialMediaFields } from "@/lib/social-utils";
import { isStored, storage } from "@/lib/storage";
import { CreatePartnerProps, ProgramProps, WorkspaceProps } from "@/lib/types";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
@@ -56,7 +57,11 @@ export const createAndEnrollPartner = async ({
],
},
include: {
- partner: true,
+ partner: {
+ include: {
+ platforms: true,
+ },
+ },
links: true,
},
});
@@ -74,6 +79,7 @@ export const createAndEnrollPartner = async ({
...programEnrollment,
id: programEnrollment.partner.id,
links: programEnrollment.links,
+ ...polyfillSocialMediaFields(programEnrollment.partner.platforms),
});
// else, if the passed tenantId is different from the existing enrollment...
} else if (partner.tenantId) {
@@ -91,7 +97,11 @@ export const createAndEnrollPartner = async ({
tenantId: partner.tenantId,
},
include: {
- partner: true,
+ partner: {
+ include: {
+ platforms: true,
+ },
+ },
links: true,
},
});
@@ -101,6 +111,9 @@ export const createAndEnrollPartner = async ({
...updatedProgramEnrollment,
id: updatedProgramEnrollment.partner.id,
links: updatedProgramEnrollment.links,
+ ...polyfillSocialMediaFields(
+ updatedProgramEnrollment.partner.platforms,
+ ),
});
}
} else if (partner.tenantId) {
@@ -162,6 +175,7 @@ export const createAndEnrollPartner = async ({
description: partner.description,
},
include: {
+ platforms: true,
programs: {
where: {
programId: program.id,
@@ -200,6 +214,7 @@ export const createAndEnrollPartner = async ({
...upsertedPartner.programs[0],
id: upsertedPartner.id,
links,
+ ...polyfillSocialMediaFields(upsertedPartner.platforms),
});
waitUntil(
diff --git a/apps/web/lib/api/partners/format-partners-for-export.ts b/apps/web/lib/api/partners/format-partners-for-export.ts
index 4972608755..18f66686a3 100644
--- a/apps/web/lib/api/partners/format-partners-for-export.ts
+++ b/apps/web/lib/api/partners/format-partners-for-export.ts
@@ -1,3 +1,4 @@
+import { polyfillSocialMediaFields } from "@/lib/social-utils";
import { exportPartnerColumns } from "@/lib/zod/schemas/partners";
import * as z from "zod/v4";
@@ -52,6 +53,11 @@ export function formatPartnersForExport(
return partners.map((partner) => {
const result: Record<string, any> = {};
+ partner = {
+ ...partner,
+ ...polyfillSocialMediaFields(partner.platforms),
+ };
+
sortedColumns.forEach((column) => {
let value = partner[column] || "";
diff --git a/apps/web/lib/api/partners/get-partners.ts b/apps/web/lib/api/partners/get-partners.ts
index 4ec2d99f2a..0d3156d4b5 100644
--- a/apps/web/lib/api/partners/get-partners.ts
+++ b/apps/web/lib/api/partners/get-partners.ts
@@ -52,7 +52,11 @@ export async function getPartners(filters: PartnerFilters) {
: {}),
},
include: {
- partner: true,
+ partner: {
+ include: {
+ platforms: true,
+ },
+ },
links: true,
},
take: pageSize,
diff --git a/apps/web/lib/api/scrapecreators/client.ts b/apps/web/lib/api/scrapecreators/client.ts
new file mode 100644
index 0000000000..0605b5b510
--- /dev/null
+++ b/apps/web/lib/api/scrapecreators/client.ts
@@ -0,0 +1,125 @@
+import { PlatformType } from "@dub/prisma/client";
+import { z } from "zod";
+
+const SCRAPECREATORS_API_BASE_URL = "https://api.scrapecreators.com";
+const SCRAPECREATORS_API_KEY = process.env.SCRAPECREATORS_API_KEY || "";
+
+export type ProfileFields = {
+ description: string;
+ platformId: string | null; // Eg. YouTube channel Id
+};
+
+// Platform-specific response schemas
+const youtubeResponseSchema = z.object({
+ description: z.string(),
+ channelId: z.string(),
+});
+
+const instagramResponseSchema = z.object({
+ data: z.object({
+ user: z.object({
+ biography: z.string(),
+ }),
+ }),
+});
+
+const errorResponseSchema = z.object({
+ message: z.string(),
+});
+
+type PlatformRequestConfig = {
+ path: string;
+ buildSearchParams: (handle: string) => URLSearchParams;
+ parseResponse: (data: unknown) => ProfileFields;
+};
+
+const PLATFORM_CONFIG: Record<
+ Exclude<PlatformType, "linkedin" | "tiktok" | "twitter" | "website">,
+ PlatformRequestConfig
+> = {
+ youtube: {
+ path: "/v1/youtube/channel",
+ buildSearchParams: (handle) => new URLSearchParams({ handle }),
+ parseResponse: (data) => {
+ const parsed = youtubeResponseSchema.parse(data);
+
+ return {
+ description: parsed.description,
+ platformId: parsed.channelId,
+ };
+ },
+ },
+ instagram: {
+ path: "/v1/instagram/profile",
+ buildSearchParams: (handle) => new URLSearchParams({ handle }),
+ parseResponse: (data) => {
+ const parsed = instagramResponseSchema.parse(data);
+
+ return {
+ description: parsed.data.user.biography,
+ platformId: null,
+ };
+ },
+ },
+};
+
+export class ScrapeCreatorsClient {
+ private apiKey: string;
+ private baseUrl: string;
+
+ constructor() {
+ if (!SCRAPECREATORS_API_KEY) {
+ throw new Error("SCRAPECREATORS_API_KEY is not configured.");
+ }
+
+ this.apiKey = SCRAPECREATORS_API_KEY;
+ this.baseUrl = SCRAPECREATORS_API_BASE_URL;
+ }
+
+ // Fetches public profile text data for a supported social platform
+ public async fetchSocialProfile({
+ platform,
+ handle,
+ }: {
+ platform: PlatformType;
+ handle: string;
+ }): Promise<ProfileFields> {
+ const config = PLATFORM_CONFIG[platform];
+
+ if (!config) {
+ throw new Error(`Unsupported platform: ${platform}`);
+ }
+
+ const endpoint = `${this.baseUrl}${config.path}`;
+ const searchParams = config.buildSearchParams(handle);
+
+ const response = await fetch(`${endpoint}?${searchParams.toString()}`, {
+ headers: {
+ "x-api-key": this.apiKey,
+ },
+ signal: AbortSignal.timeout(10000), // 10 second timeout
+ });
+
+ const jsonResponse = await response.json();
+
+ if (!response.ok) {
+ console.error("[ScrapeCreators] Failed to fetch account", {
+ ...jsonResponse,
+ platform,
+ handle,
+ });
+
+ const parsedError = errorResponseSchema.safeParse(jsonResponse);
+
+ throw new Error(
+ parsedError.success
+ ? parsedError.data.message
+ : "Failed to fetch account profile.",
+ );
+ }
+
+ return config.parseResponse(jsonResponse);
+ }
+}
+
+export const scrapeCreatorsClient = new ScrapeCreatorsClient();
diff --git a/apps/web/lib/auth/partner.ts b/apps/web/lib/auth/partner.ts
index d734e22697..1c011ca2fa 100644
--- a/apps/web/lib/auth/partner.ts
+++ b/apps/web/lib/auth/partner.ts
@@ -4,6 +4,7 @@ import { PartnerProps } from "@/lib/types";
import { prisma } from "@dub/prisma";
import { PartnerUser } from "@dub/prisma/client";
import { getSearchParams, PARTNERS_DOMAIN } from "@dub/utils";
+import { partnerPlatformSchema } from "../zod/schemas/partners";
import { Permission } from "./partner-users/partner-user-permissions";
import { throwIfNoPermission } from "./partner-users/throw-if-no-permission";
import { rateLimitRequest } from "./rate-limit-request";
@@ -117,6 +118,7 @@ export const withPartnerProfile = (
industryInterests: true,
preferredEarningStructures: true,
salesChannels: true,
+ platforms: true,
},
},
},
@@ -141,6 +143,7 @@ export const withPartnerProfile = (
industryInterests,
preferredEarningStructures,
salesChannels,
+ platforms,
...partner
} = partnerUser.partner;
@@ -160,6 +163,7 @@ export const withPartnerProfile = (
salesChannels: salesChannels.map(
({ salesChannel }) => salesChannel,
),
+ platforms: partnerPlatformSchema.array().parse(platforms),
} as Omit<PartnerProps, "role" | "userId">,
partnerUser: {
userId: partnerUser.userId,
diff --git a/apps/web/lib/firstpromoter/import-partners.ts b/apps/web/lib/firstpromoter/import-partners.ts
index b66465db22..63e8d21135 100644
--- a/apps/web/lib/firstpromoter/import-partners.ts
+++ b/apps/web/lib/firstpromoter/import-partners.ts
@@ -2,11 +2,13 @@ import { prisma } from "@dub/prisma";
import {
PartnerGroup,
PartnerGroupDefaultLink,
+ PlatformType,
Program,
} from "@dub/prisma/client";
import { isRejected, nanoid } from "@dub/utils";
import { createId } from "../api/create-id";
import { bulkCreateLinks } from "../api/links";
+import { upsertPartnerPlatform } from "../api/partner-profile/upsert-partner-platform";
import { DEFAULT_PARTNER_GROUP } from "../zod/schemas/groups";
import { FirstPromoterApi } from "./api";
import { firstPromoterImporter, MAX_BATCHES } from "./importer";
@@ -123,12 +125,6 @@ async function createPartnerAndLinks({
image: affiliate.profile.avatar,
description: affiliate.profile.description,
country: affiliate.profile.country,
- website: affiliate.profile.website,
- youtube: affiliate.profile.youtube_url,
- twitter: affiliate.profile.twitter_url,
- linkedin: affiliate.profile.linkedin_url,
- instagram: affiliate.profile.instagram_url,
- tiktok: affiliate.profile.tiktok_url,
companyName: affiliate.profile.company_name,
invoiceSettings: {
...(affiliate.profile.address && {
@@ -139,6 +135,40 @@ async function createPartnerAndLinks({
update: {},
});
+ const socialPlatformFields: Record<PlatformType, string | null> = {
+ website: affiliate.profile.website,
+ youtube: affiliate.profile.youtube_url,
+ twitter: affiliate.profile.twitter_url,
+ linkedin: affiliate.profile.linkedin_url,
+ instagram: affiliate.profile.instagram_url,
+ tiktok: affiliate.profile.tiktok_url,
+ };
+
+ const socialPlatformEntries = Object.entries(socialPlatformFields) as [
+ PlatformType,
+ string | null,
+ ][];
+
+ const entriesWithHandles = socialPlatformEntries.filter(
+ ([, identifier]) => typeof identifier === "string" && identifier.trim().length > 0,
+ );
+
+ if (entriesWithHandles.length > 0) {
+ await Promise.allSettled(
+ entriesWithHandles.map(([platform, identifier]) =>
+ upsertPartnerPlatform({
+ where: {
+ partnerId: partner.id,
+ type: platform,
+ },
+ data: {
+ identifier: identifier!.trim(),
+ },
+ }),
+ ),
+ );
+ }
+
const programEnrollment = await prisma.programEnrollment.upsert({
where: {
partnerId_programId: {
diff --git a/apps/web/lib/network/get-discoverability-requirements.ts b/apps/web/lib/network/get-discoverability-requirements.ts
index f1a34552bb..aaa4235aa4 100644
--- a/apps/web/lib/network/get-discoverability-requirements.ts
+++ b/apps/web/lib/network/get-discoverability-requirements.ts
@@ -3,10 +3,7 @@ import {
EXCLUDED_PROGRAM_IDS,
PARTNER_NETWORK_MIN_COMMISSIONS_CENTS,
} from "../constants/partner-profile";
-import {
- ONLINE_PRESENCE_FIELDS,
- PartnerOnlinePresenceFields,
-} from "../partners/online-presence";
+import { ONLINE_PRESENCE_FIELDS } from "../partners/online-presence";
import { EnrolledPartnerProps, PartnerProps } from "../types";
export const partnerHasEarnedCommissions = (
@@ -56,11 +53,11 @@ export function getDiscoverabilityRequirements({
}: {
partner: Pick<
PartnerProps,
- | PartnerOnlinePresenceFields
| "description"
| "monthlyTraffic"
| "preferredEarningStructures"
| "salesChannels"
+ | "platforms"
>;
programEnrollments: Pick<
EnrolledPartnerProps,
@@ -76,7 +73,7 @@ export function getDiscoverabilityRequirements({
label: "Connect your website or social account",
href: "#sites",
completed: ONLINE_PRESENCE_FIELDS.some(
- (field) => field.data(partner).value, // TODO: update this to also check for "verified" in the future
+ (field) => field.data(partner.platforms).value, // TODO: update this to also check for "verified" in the future
),
},
{
diff --git a/apps/web/lib/partners/complete-program-applications.ts b/apps/web/lib/partners/complete-program-applications.ts
index af6a28adb7..2c3eb3025b 100644
--- a/apps/web/lib/partners/complete-program-applications.ts
+++ b/apps/web/lib/partners/complete-program-applications.ts
@@ -1,10 +1,11 @@
import { prisma } from "@dub/prisma";
-import { Prisma } from "@dub/prisma/client";
+import { Prisma, PlatformType } from "@dub/prisma/client";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { createId } from "../api/create-id";
import { detectAndRecordFraudApplication } from "../api/fraud/detect-record-fraud-application";
import { notifyPartnerApplication } from "../api/partners/notify-partner-application";
import { qstash } from "../cron";
+import { buildSocialPlatformLookup } from "../social-utils";
import { sendWorkspaceWebhook } from "../webhook/publish";
import { partnerApplicationWebhookSchema } from "../zod/schemas/program-application";
import {
@@ -26,6 +27,7 @@ export async function completeProgramApplications(userEmail: string) {
partnerId: true,
partner: {
include: {
+ platforms: true,
programs: {
select: {
programId: true,
@@ -130,29 +132,31 @@ export async function completeProgramApplications(userEmail: string) {
(p) => p.programId === programApplication.programId,
);
+ const socialPlatforms = buildSocialPlatformLookup(partner.platforms);
+
const missingSocialFields = {
website:
- application.website && !partner.website
+ application.website && !socialPlatforms.website?.identifier
? application.website
: undefined,
youtube:
- application.youtube && !partner.youtube
+ application.youtube && !socialPlatforms.youtube?.identifier
? application.youtube
: undefined,
twitter:
- application.twitter && !partner.twitter
+ application.twitter && !socialPlatforms.twitter?.identifier
? application.twitter
: undefined,
linkedin:
- application.linkedin && !partner.linkedin
+ application.linkedin && !socialPlatforms.linkedin?.identifier
? application.linkedin
: undefined,
instagram:
- application.instagram && !partner.instagram
+ application.instagram && !socialPlatforms.instagram?.identifier
? application.instagram
: undefined,
tiktok:
- application.tiktok && !partner.tiktok
+ application.tiktok && !socialPlatforms.tiktok?.identifier
? application.tiktok
: undefined,
};
@@ -179,9 +183,15 @@ export async function completeProgramApplications(userEmail: string) {
// if the application has any website or social fields but the partner doesn't have the corresponding one (maybe they forgot to add during onboarding)
// update the partner to use the website they applied with
hasMissingSocialFields &&
- prisma.partner.update({
- where: { id: partner.id },
- data: missingSocialFields,
+ prisma.partnerPlatform.createMany({
+ data: Object.entries(missingSocialFields)
+ .filter(([, identifier]) => identifier !== undefined)
+ .map(([platform, identifier]) => ({
+ partnerId: partner.id,
+ type: platform as PlatformType,
+ identifier: identifier as string,
+ })),
+ skipDuplicates: true,
}),
// Auto-approve the partner if the group has auto-approval enabled
diff --git a/apps/web/lib/partners/online-presence.ts b/apps/web/lib/partners/online-presence.ts
index fb979aecc1..e92c1a107a 100644
--- a/apps/web/lib/partners/online-presence.ts
+++ b/apps/web/lib/partners/online-presence.ts
@@ -8,30 +8,12 @@ import {
YouTube,
} from "@dub/ui/icons";
import { getPrettyUrl, nFormatter } from "@dub/utils";
-import { EnrolledPartnerExtendedProps } from "../types";
-
-export type PartnerOnlinePresenceFields =
- | "website"
- | "websiteVerifiedAt"
- | "youtube"
- | "youtubeSubscriberCount"
- | "youtubeVerifiedAt"
- | "youtubeViewCount"
- | "twitter"
- | "twitterVerifiedAt"
- | "linkedin"
- | "linkedinVerifiedAt"
- | "instagram"
- | "instagramVerifiedAt"
- | "tiktok"
- | "tiktokVerifiedAt";
+import { PartnerPlatformProps } from "../types";
export const ONLINE_PRESENCE_FIELDS: {
label: string;
icon: Icon;
- data: (
- partner: Pick<EnrolledPartnerExtendedProps, PartnerOnlinePresenceFields>,
- ) => {
+ data: (platforms: PartnerPlatformProps[]) => {
value?: string | null;
verified: boolean;
href?: string | null;
@@ -41,63 +23,97 @@ export const ONLINE_PRESENCE_FIELDS: {
{
label: "Website",
icon: Globe,
- data: (partner) => ({
- value: partner.website ? getPrettyUrl(partner.website) : null,
- verified: !!partner.websiteVerifiedAt,
- href: partner.website,
- }),
+ data: (platforms) => {
+ const website = platforms.find((p) => p.type === "website");
+
+ return {
+ value: website ? getPrettyUrl(website.identifier) : null,
+ verified: !!website?.verifiedAt,
+ href: website?.identifier,
+ };
+ },
},
{
label: "YouTube",
icon: YouTube,
- data: (partner) => ({
- value: partner.youtube ? `@${partner.youtube}` : null,
- verified: !!partner.youtubeVerifiedAt,
- href: `https://youtube.com/@${partner.youtube}`,
- info: [
- partner.youtubeSubscriberCount && partner.youtubeSubscriberCount > 0
- ? `${nFormatter(partner.youtubeSubscriberCount)} subscribers`
- : null,
- partner.youtubeViewCount && partner.youtubeViewCount > 0
- ? `${nFormatter(partner.youtubeViewCount)} views`
+ data: (platforms) => {
+ const youtube = platforms.find((p) => p.type === "youtube");
+
+ return {
+ value: youtube?.identifier ? `@${youtube.identifier}` : null,
+ verified: !!youtube?.verifiedAt,
+ href: youtube?.identifier
+ ? `https://youtube.com/@${youtube.identifier}`
: null,
- ].filter(Boolean),
- }),
+ info: [
+ youtube?.subscribers && youtube.subscribers > 0
+ ? `${nFormatter(Number(youtube.subscribers))} subscribers`
+ : null,
+ youtube?.views && youtube.views > 0
+ ? `${nFormatter(Number(youtube.views))} views`
+ : null,
+ ].filter(Boolean),
+ };
+ },
},
{
label: "X/Twitter",
icon: Twitter,
- data: (partner) => ({
- value: partner.twitter ? `@${partner.twitter}` : null,
- verified: !!partner.twitterVerifiedAt,
- href: `https://x.com/${partner.twitter}`,
- }),
+ data: (platforms) => {
+ const twitter = platforms.find((p) => p.type === "twitter");
+
+ return {
+ value: twitter ? `@${twitter.identifier}` : null,
+ verified: !!twitter?.verifiedAt,
+ href: twitter?.identifier
+ ? `https://x.com/${twitter.identifier}`
+ : null,
+ };
+ },
},
{
label: "LinkedIn",
icon: LinkedIn,
- data: (partner) => ({
- value: partner.linkedin,
- verified: !!partner.linkedinVerifiedAt,
- href: `https://linkedin.com/in/${partner.linkedin}`,
- }),
+ data: (platforms) => {
+ const linkedin = platforms.find((p) => p.type === "linkedin");
+
+ return {
+ value: linkedin ? linkedin.identifier : null,
+ verified: !!linkedin?.verifiedAt,
+ href: linkedin?.identifier
+ ? `https://linkedin.com/in/${linkedin.identifier}`
+ : null,
+ };
+ },
},
{
label: "Instagram",
icon: Instagram,
- data: (partner) => ({
- value: partner.instagram ? `@${partner.instagram}` : null,
- verified: !!partner.instagramVerifiedAt,
- href: `https://instagram.com/${partner.instagram}`,
- }),
+ data: (platforms) => {
+ const instagram = platforms.find((p) => p.type === "instagram");
+
+ return {
+ value: instagram ? `@${instagram.identifier}` : null,
+ verified: !!instagram?.verifiedAt,
+ href: instagram?.identifier
+ ? `https://instagram.com/${instagram.identifier}`
+ : null,
+ };
+ },
},
{
label: "Tiktok",
icon: TikTok,
- data: (partner) => ({
- value: partner.tiktok ? `@${partner.tiktok}` : null,
- verified: !!partner.tiktokVerifiedAt,
- href: `https://tiktok.com/@${partner.tiktok}`,
- }),
+ data: (platforms) => {
+ const tiktok = platforms.find((p) => p.type === "tiktok");
+
+ return {
+ value: tiktok ? `@${tiktok.identifier}` : null,
+ verified: !!tiktok?.verifiedAt,
+ href: tiktok?.identifier
+ ? `https://tiktok.com/@${tiktok.identifier}`
+ : null,
+ };
+ },
},
];
diff --git a/apps/web/lib/social-utils.ts b/apps/web/lib/social-utils.ts
index 9c21848920..2bea196391 100644
--- a/apps/web/lib/social-utils.ts
+++ b/apps/web/lib/social-utils.ts
@@ -1,17 +1,16 @@
-export type SocialPlatform =
- | "youtube"
- | "twitter"
- | "linkedin"
- | "instagram"
- | "tiktok";
+import { PlatformType } from "@dub/prisma/client";
interface SocialPlatformConfig {
patterns: RegExp[];
allowedChars: RegExp;
maxLength?: number;
+ name: string;
}
-const PLATFORM_CONFIGS: Record<SocialPlatform, SocialPlatformConfig> = {
+export const SOCIAL_PLATFORM_CONFIGS: Record<
+ Exclude<PlatformType, "website">,
+ SocialPlatformConfig
+> = {
youtube: {
patterns: [
/^(?:.*\.)?(?:youtube\.com|youtu\.be)\/(?:channel\/|c\/|user\/|@)?([^\/\?]+)/i,
@@ -19,6 +18,7 @@ const PLATFORM_CONFIGS: Record<SocialPlatform, SocialPlatformConfig> = {
],
allowedChars: /[^\w.-]/g,
maxLength: 30,
+ name: "YouTube",
},
twitter: {
patterns: [
@@ -27,21 +27,25 @@ const PLATFORM_CONFIGS: Record<SocialPlatform, SocialPlatformConfig> = {
],
allowedChars: /[^\w]/g,
maxLength: 15,
+ name: "Twitter",
},
linkedin: {
patterns: [/^(?:.*\.)?linkedin\.com\/(?:in\/)?([^\/\?]+)/i],
allowedChars: /[^\w-]/g,
maxLength: 30,
+ name: "LinkedIn",
},
instagram: {
patterns: [/^(?:.*\.)?instagram\.com\/([^\/\?]+)/i, /^@([^\/\?]+)/i],
allowedChars: /[^\w.]/g,
maxLength: 30,
+ name: "Instagram",
},
tiktok: {
patterns: [/^(?:.*\.)?tiktok\.com\/(?:@)?([^\/\?]+)/i, /^@([^\/\?]+)/i],
allowedChars: /[^\w.]/g,
maxLength: 24,
+ name: "TikTok",
},
};
@@ -65,7 +69,7 @@ export const sanitizeWebsite = (input: string | null | undefined) => {
export const sanitizeSocialHandle = (
input: string | null | undefined,
- platform: SocialPlatform,
+ platform: PlatformType,
) => {
if (!input || typeof input !== "string") {
return null;
@@ -78,7 +82,8 @@ export const sanitizeSocialHandle = (
handle = handle.replace(/^https?:\/\//i, "").replace(/^www\./i, "");
- const { patterns, allowedChars, maxLength } = PLATFORM_CONFIGS[platform];
+ const { patterns, allowedChars, maxLength } =
+ SOCIAL_PLATFORM_CONFIGS[platform];
for (const pattern of patterns) {
const match = handle.match(pattern);
@@ -100,3 +105,40 @@ export const sanitizeSocialHandle = (
return handle || null;
};
+
+// Converts an array of platform objects into a key-value object
+// for easy lookup by platform name. Returns null for platforms not found.
+export function buildSocialPlatformLookup<
+ T extends { type: PlatformType },
+>(platforms: T[]): Record<PlatformType, T | null> {
+ const result = {
+ website: null,
+ youtube: null,
+ twitter: null,
+ linkedin: null,
+ instagram: null,
+ tiktok: null,
+ } as Record<PlatformType, T | null>;
+
+ for (const platform of platforms) {
+ result[platform.type] = platform;
+ }
+
+ return result;
+}
+
+// Polyfills social media fields from platforms array for backward compatibility
+export function polyfillSocialMediaFields<
+ T extends { type: PlatformType; identifier: string | null },
+>(platforms: T[]) {
+ const platformsMap = buildSocialPlatformLookup(platforms);
+
+ return {
+ website: platformsMap["website"]?.identifier ?? null,
+ youtube: platformsMap["youtube"]?.identifier ?? null,
+ twitter: platformsMap["twitter"]?.identifier ?? null,
+ linkedin: platformsMap["linkedin"]?.identifier ?? null,
+ instagram: platformsMap["instagram"]?.identifier ?? null,
+ tiktok: platformsMap["tiktok"]?.identifier ?? null,
+ };
+}
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index a64d3bce12..ee1ce9aee7 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -94,6 +94,7 @@ import {
createPartnerSchema,
EnrolledPartnerSchema,
EnrolledPartnerSchemaExtended,
+ partnerPlatformSchema,
PartnerRewindSchema,
PartnerSchema,
WebhookPartnerSchema,
@@ -454,9 +455,12 @@ export type PartnerEarningsResponse = z.infer<typeof PartnerEarningsSchema>;
export type CustomerProps = z.infer<typeof CustomerSchema>;
+export type PartnerPlatformProps = z.infer<typeof partnerPlatformSchema>;
+
export type PartnerProps = z.infer<typeof PartnerSchema> & {
role: PartnerRole;
userId: string;
+ platforms: PartnerPlatformProps[];
};
export type PartnerRewindProps = z.infer<typeof PartnerRewindSchema>;
@@ -468,7 +472,9 @@ export type PartnerProfileCustomerProps = z.infer<
export type PartnerProfileLinkProps = z.infer<typeof PartnerProfileLinkSchema>;
-export type EnrolledPartnerProps = z.infer<typeof EnrolledPartnerSchema>;
+export type EnrolledPartnerProps = z.infer<typeof EnrolledPartnerSchema> & {
+ platforms: PartnerPlatformProps[];
+};
export type NetworkPartnerProps = z.infer<typeof NetworkPartnerSchema>;
@@ -484,7 +490,9 @@ export type NetworkProgramExtendedProps = z.infer<
export type EnrolledPartnerExtendedProps = z.infer<
typeof EnrolledPartnerSchemaExtended
->;
+> & {
+ platforms: PartnerPlatformProps[];
+};
export type DiscountProps = z.infer<typeof DiscountSchema>;
diff --git a/apps/web/lib/zod/schemas/partner-network.ts b/apps/web/lib/zod/schemas/partner-network.ts
index be591bd788..d39ab158d1 100644
--- a/apps/web/lib/zod/schemas/partner-network.ts
+++ b/apps/web/lib/zod/schemas/partner-network.ts
@@ -1,6 +1,6 @@
import * as z from "zod/v4";
import { booleanQuerySchema, getPaginationQuerySchema } from "./misc";
-import { PartnerSchema } from "./partners";
+import { PartnerSchema, partnerPlatformSchema } from "./partners";
export const PARTNER_CONVERSION_SCORES = [
"unknown",
@@ -68,25 +68,9 @@ export const NetworkPartnerSchema = PartnerSchema.pick({
description: true,
createdAt: true,
trustedAt: true,
-
monthlyTraffic: true,
preferredEarningStructures: true,
salesChannels: true,
-
- website: true,
- websiteVerifiedAt: true,
- youtube: true,
- youtubeVerifiedAt: true,
- youtubeSubscriberCount: true,
- youtubeViewCount: true,
- twitter: true,
- twitterVerifiedAt: true,
- linkedin: true,
- linkedinVerifiedAt: true,
- instagram: true,
- instagramVerifiedAt: true,
- tiktok: true,
- tiktokVerifiedAt: true,
}).extend({
lastConversionAt: z.date().nullable(),
conversionScore: PartnerConversionScoreSchema,
@@ -95,6 +79,7 @@ export const NetworkPartnerSchema = PartnerSchema.pick({
ignoredAt: z.date().nullable(),
recruitedAt: z.date().nullable(),
categories: z.array(z.string()),
+ platforms: z.array(partnerPlatformSchema),
});
export const updateDiscoveredPartnerSchema = z.object({
diff --git a/apps/web/lib/zod/schemas/partners.ts b/apps/web/lib/zod/schemas/partners.ts
index 22fbf32595..b2f6fb370d 100644
--- a/apps/web/lib/zod/schemas/partners.ts
+++ b/apps/web/lib/zod/schemas/partners.ts
@@ -3,6 +3,7 @@ import {
MonthlyTraffic,
PartnerBannedReason,
PartnerProfileType,
+ PlatformType,
PreferredEarningStructure,
ProgramEnrollmentStatus,
SalesChannel,
@@ -183,7 +184,7 @@ export const getPartnersQuerySchemaExtended = getPartnersQuerySchema.extend({
.transform((v) => (Array.isArray(v) ? v : v.split(",")))
.optional(),
groupId: z.string().optional(),
- includeOnlinePresenceVerification: booleanQuerySchema.optional(),
+ includePartnerPlatforms: booleanQuerySchema.optional(),
});
export const partnersExportQuerySchema = getPartnersQuerySchemaExtended
@@ -206,40 +207,41 @@ export const partnersCountQuerySchema = getPartnersQuerySchemaExtended
groupBy: z.enum(["status", "country", "groupId"]).optional(),
});
+export const partnerPlatformSchema = z.object({
+ type: z.enum(PlatformType),
+ identifier: z.string(),
+ verifiedAt: z.date().nullable(),
+ platformId: z.string().nullable(),
+ subscribers: z.bigint().default(BigInt(0)),
+ posts: z.bigint().default(BigInt(0)),
+ views: z.bigint().default(BigInt(0)),
+});
+
export const PartnerOnlinePresenceSchema = z.object({
website: z
.string()
.nullish()
.describe("The partner's website URL (including the https protocol)."),
- websiteTxtRecord: z.string().nullish(),
- websiteVerifiedAt: z.date().nullish(),
youtube: z
.string()
.nullish()
.describe("The partner's YouTube channel username (e.g. `johndoe`)."),
- youtubeVerifiedAt: z.date().nullish(),
- youtubeSubscriberCount: z.number().nullish(),
- youtubeViewCount: z.number().nullish(),
twitter: z
.string()
.nullish()
.describe("The partner's Twitter username (e.g. `johndoe`)."),
- twitterVerifiedAt: z.date().nullish(),
linkedin: z
.string()
.nullish()
.describe("The partner's LinkedIn username (e.g. `johndoe`)."),
- linkedinVerifiedAt: z.date().nullish(),
instagram: z
.string()
.nullish()
.describe("The partner's Instagram username (e.g. `johndoe`)."),
- instagramVerifiedAt: z.date().nullish(),
tiktok: z
.string()
.nullish()
.describe("The partner's TikTok username (e.g. `johndoe`)."),
- tiktokVerifiedAt: z.date().nullish(),
});
export const MAX_PARTNER_INDUSTRY_INTERESTS = 8;
@@ -469,14 +471,17 @@ export const EnrolledPartnerSchemaExtended = EnrolledPartnerSchema.extend({
lastLeadAt: z.date().nullish(),
lastConversionAt: z.date().nullish(),
customerDataSharingEnabledAt: z.date().nullish(),
- ...PartnerSchema.pick({
- monthlyTraffic: true,
- industryInterests: true,
- preferredEarningStructures: true,
- salesChannels: true,
- }).shape,
- ...PartnerOnlinePresenceSchema.shape,
-});
+ platforms: z.array(partnerPlatformSchema).nullable(),
+})
+ .extend(
+ PartnerSchema.pick({
+ monthlyTraffic: true,
+ industryInterests: true,
+ preferredEarningStructures: true,
+ salesChannels: true,
+ }).shape,
+ )
+ .extend(PartnerOnlinePresenceSchema.shape);
export const WebhookPartnerSchema = PartnerSchema.pick({
id: true,
diff --git a/apps/web/scripts/migrations/backfill-discoverableat.ts b/apps/web/scripts/migrations/backfill-discoverableat.ts
index e6c6ef4b4a..d59c5be687 100644
--- a/apps/web/scripts/migrations/backfill-discoverableat.ts
+++ b/apps/web/scripts/migrations/backfill-discoverableat.ts
@@ -1,3 +1,4 @@
+import { buildSocialPlatformLookup } from "@/lib/social-utils";
import { prisma } from "@dub/prisma";
import { Prisma } from "@dub/prisma/client";
import { ACME_PROGRAM_ID } from "@dub/utils";
@@ -19,55 +20,40 @@ async function main() {
},
},
},
- OR: [
- {
- website: {
- not: null,
- },
- },
- {
- youtube: {
- not: null,
- },
- },
- {
- twitter: {
- not: null,
- },
- },
- {
- linkedin: {
- not: null,
- },
- },
- {
- instagram: {
- not: null,
- },
- },
- {
- tiktok: {
- not: null,
- },
- },
- ],
+ platforms: {
+ some: {},
+ },
};
+
const partners = await prisma.partner.findMany({
where,
+ include: {
+ platforms: true,
+ },
});
- console.table(partners, [
- "name",
- "email",
- "website",
- "youtube",
- "twitter",
- "linkedin",
- "instagram",
- "tiktok",
- ]);
+
+ // Format partners for display with platform handles
+ const partnersForDisplay = partners.map((partner) => {
+ const platformsMap = buildSocialPlatformLookup(partner.platforms);
+
+ return {
+ name: partner.name,
+ email: partner.email,
+ website: platformsMap.website?.identifier || null,
+ youtube: platformsMap.youtube?.identifier || null,
+ twitter: platformsMap.twitter?.identifier || null,
+ linkedin: platformsMap.linkedin?.identifier || null,
+ instagram: platformsMap.instagram?.identifier || null,
+ tiktok: platformsMap.tiktok?.identifier || null,
+ };
+ });
+
+ console.table(partnersForDisplay);
+
const count = await prisma.partner.count({
where,
});
+
console.log(`Found ${count} partners to backfill`);
const res = await prisma.partner.updateMany({
diff --git a/apps/web/scripts/migrations/backfill-partner-platforms.ts b/apps/web/scripts/migrations/backfill-partner-platforms.ts
new file mode 100644
index 0000000000..f0c1f69f30
--- /dev/null
+++ b/apps/web/scripts/migrations/backfill-partner-platforms.ts
@@ -0,0 +1,161 @@
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
+import "dotenv-flow/config";
+
+async function main() {
+ let startingAfter: string | undefined = undefined;
+
+ while (true) {
+ console.log(
+ `Fetching partners${startingAfter ? ` starting after ${startingAfter}` : ""}...`,
+ );
+
+ const partners = await prisma.partner.findMany({
+ where: {
+ OR: [
+ {
+ website: {
+ not: null,
+ },
+ },
+ {
+ youtube: {
+ not: null,
+ },
+ },
+ {
+ twitter: {
+ not: null,
+ },
+ },
+ {
+ linkedin: {
+ not: null,
+ },
+ },
+ {
+ instagram: {
+ not: null,
+ },
+ },
+ {
+ tiktok: {
+ not: null,
+ },
+ },
+ ],
+ },
+ take: 1000,
+ orderBy: {
+ id: "asc",
+ },
+ ...(startingAfter
+ ? {
+ skip: 1,
+ cursor: {
+ id: startingAfter,
+ },
+ }
+ : {}),
+ });
+
+ if (partners.length === 0) {
+ console.log("Finished processing partners.");
+ break;
+ }
+
+ const partnerPlatforms: Omit<
+ Prisma.PartnerPlatformCreateManyInput,
+ "id" | "createdAt" | "updatedAt"
+ >[] = [];
+
+ for (const partner of partners) {
+ const commonFields = {
+ partnerId: partner.id,
+ posts: BigInt(0),
+ views: BigInt(0),
+ subscribers: BigInt(0),
+ metadata: Prisma.DbNull,
+ platformId: null,
+ };
+
+ if (partner.website) {
+ partnerPlatforms.push({
+ ...commonFields,
+ type: "website",
+ identifier: partner.website,
+ verifiedAt: partner.websiteVerifiedAt,
+ metadata: partner.websiteTxtRecord
+ ? { websiteTxtRecord: partner.websiteTxtRecord }
+ : Prisma.DbNull,
+ });
+ }
+
+ if (partner.youtube) {
+ partnerPlatforms.push({
+ ...commonFields,
+ type: "youtube",
+ identifier: partner.youtube,
+ platformId: partner.youtubeChannelId,
+ verifiedAt: partner.youtubeVerifiedAt,
+ posts: BigInt(partner.youtubeVideoCount),
+ views: BigInt(partner.youtubeViewCount),
+ subscribers: BigInt(partner.youtubeSubscriberCount),
+ });
+ }
+
+ if (partner.twitter) {
+ partnerPlatforms.push({
+ ...commonFields,
+ type: "twitter",
+ identifier: partner.twitter,
+ verifiedAt: partner.twitterVerifiedAt,
+ });
+ }
+
+ if (partner.linkedin) {
+ partnerPlatforms.push({
+ ...commonFields,
+ type: "linkedin",
+ identifier: partner.linkedin,
+ verifiedAt: partner.linkedinVerifiedAt,
+ });
+ }
+
+ if (partner.instagram) {
+ partnerPlatforms.push({
+ ...commonFields,
+ type: "instagram",
+ identifier: partner.instagram,
+ verifiedAt: partner.instagramVerifiedAt,
+ });
+ }
+
+ if (partner.tiktok) {
+ partnerPlatforms.push({
+ ...commonFields,
+ type: "tiktok",
+ identifier: partner.tiktok,
+ verifiedAt: partner.tiktokVerifiedAt,
+ });
+ }
+ }
+
+ if (partnerPlatforms.length > 0) {
+ console.table(partnerPlatforms);
+
+ const { count } = await prisma.partnerPlatform.createMany({
+ data: partnerPlatforms,
+ skipDuplicates: true,
+ });
+
+ console.log(`Added ${count} partner platforms.`);
+ }
+
+ startingAfter = partners[partners.length - 1].id;
+
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ }
+}
+
+main();
diff --git a/apps/web/scripts/partners/sanitize-social-handles.ts b/apps/web/scripts/partners/sanitize-social-handles.ts
deleted file mode 100644
index 9370afbf93..0000000000
--- a/apps/web/scripts/partners/sanitize-social-handles.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { sanitizeSocialHandle, type SocialPlatform } from "@/lib/social-utils";
-import { prisma } from "@dub/prisma";
-import { Partner } from "@dub/prisma/client";
-import { deepEqual } from "@dub/utils";
-import "dotenv-flow/config";
-
-async function main() {
- const partners = await prisma.partner.findMany({
- where: {
- OR: [
- { youtube: { contains: "@" } },
- { youtube: { contains: "http" } },
- { twitter: { contains: "@" } },
- { twitter: { contains: "http" } },
- { linkedin: { contains: "@" } },
- { linkedin: { contains: "http" } },
- { instagram: { contains: "@" } },
- { instagram: { contains: "http" } },
- { tiktok: { contains: "@" } },
- { tiktok: { contains: "http" } },
- ],
- },
- select: {
- id: true,
- youtube: true,
- twitter: true,
- linkedin: true,
- instagram: true,
- tiktok: true,
- },
- take: 50,
- });
-
- if (partners.length === 0) {
- console.log("No partners found processing.");
- return;
- }
-
- console.log("Partners with social handles");
- console.table(partners);
-
- const updatedPartners: Pick<
- Partner,
- "id" | "youtube" | "twitter" | "linkedin" | "instagram" | "tiktok"
- >[] = [];
-
- for (const { id, ...socialHandles } of partners) {
- let updatedSocialHandles = {
- ...socialHandles,
- };
-
- for (const [platform, value] of Object.entries(socialHandles)) {
- updatedSocialHandles[platform] = sanitizeSocialHandle(
- value,
- platform as SocialPlatform,
- );
- }
-
- const needsUpdate =
- deepEqual(socialHandles, updatedSocialHandles) === false;
-
- if (needsUpdate) {
- updatedPartners.push({
- id,
- ...updatedSocialHandles,
- });
-
- await prisma.partner.update({
- where: {
- id,
- },
- data: updatedSocialHandles,
- });
- }
- }
-
- console.log("Updated partners");
- console.table(updatedPartners);
-}
-
-main();
diff --git a/apps/web/scripts/partners/sanitize-websites.ts b/apps/web/scripts/partners/sanitize-websites.ts
deleted file mode 100644
index 0bc297bbb8..0000000000
--- a/apps/web/scripts/partners/sanitize-websites.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { sanitizeWebsite } from "@/lib/social-utils";
-import { prisma } from "@dub/prisma";
-import { Partner } from "@dub/prisma/client";
-import "dotenv-flow/config";
-
-async function main() {
- const partners = await prisma.partner.findMany({
- where: {
- AND: [
- {
- website: { not: "" },
- },
- {
- website: { not: null },
- },
- {
- OR: [
- { website: { not: { contains: "http" } } },
- { website: { contains: "?" } },
- ],
- },
- ],
- },
- select: {
- id: true,
- website: true,
- },
- take: 50,
- });
-
- if (partners.length === 0) {
- console.log("No partners found.");
- return;
- }
-
- console.log("Partners with websites");
- console.table(partners);
-
- const updatedPartners: Pick<Partner, "id" | "website">[] = [];
-
- for (const { id, website } of partners) {
- let updatedWebsite = sanitizeWebsite(website);
-
- const needsUpdate = updatedWebsite !== website;
-
- if (needsUpdate) {
- updatedPartners.push({
- id,
- website: updatedWebsite,
- });
-
- await prisma.partner.update({
- where: {
- id,
- },
- data: {
- website: updatedWebsite,
- },
- });
- }
- }
-
- console.log("Updated partners");
- console.table(updatedPartners);
-}
-
-main();
diff --git a/apps/web/tests/partners/resource.ts b/apps/web/tests/partners/resource.ts
index bfab221ee9..cc03a89cd4 100644
--- a/apps/web/tests/partners/resource.ts
+++ b/apps/web/tests/partners/resource.ts
@@ -30,10 +30,4 @@ export const normalizedPartnerDateFields = z.object({
bannedAt: z.string().nullish(),
payoutsEnabledAt: z.string().nullish(),
trustedAt: z.string().nullish(),
- websiteVerifiedAt: z.string().nullish(),
- youtubeVerifiedAt: z.string().nullish(),
- twitterVerifiedAt: z.string().nullish(),
- linkedinVerifiedAt: z.string().nullish(),
- instagramVerifiedAt: z.string().nullish(),
- tiktokVerifiedAt: z.string().nullish(),
});
diff --git a/apps/web/ui/modals/domain-verification-modal.tsx b/apps/web/ui/modals/domain-verification-modal.tsx
index 84d05cd29b..c35defb109 100644
--- a/apps/web/ui/modals/domain-verification-modal.tsx
+++ b/apps/web/ui/modals/domain-verification-modal.tsx
@@ -35,11 +35,16 @@ function DomainVerificationModalInner({
domain,
txtRecord,
}: DomainVerificationModalProps) {
- const { partner, mutate: mutatePartner } = usePartnerProfile();
+ const { mutate: mutatePartner } = usePartnerProfile();
const { executeAsync, status } = useAction(verifyDomainAction, {
+ onSuccess: async () => {
+ toast.success("Your domain verified successfully!");
+ setShowDomainVerificationModal(false);
+ await mutatePartner();
+ },
onError: ({ error }) => {
- console.warn("Failed to verify domain", error.serverError);
+ toast.error(error.serverError || "Failed to verify domain.");
},
});
@@ -86,22 +91,7 @@ function DomainVerificationModalInner({
text="Verify"
className="h-8 w-fit px-3"
loading={status === "executing" || status === "hasSucceeded"}
- onClick={async () => {
- const result = await executeAsync();
-
- if (!result?.data?.success || !result.data.websiteVerifiedAt) {
- toast.error(`Failed to verify domain: ${result?.serverError}`);
- return;
- }
-
- toast.success("Domain verified successfully!");
- if (partner)
- mutatePartner({
- ...partner,
- websiteVerifiedAt: new Date(result.data.websiteVerifiedAt),
- });
- setShowDomainVerificationModal(false);
- }}
+ onClick={async () => await executeAsync()}
/>
</div>
</>
diff --git a/apps/web/ui/modals/social-verification-by-code-modal.tsx b/apps/web/ui/modals/social-verification-by-code-modal.tsx
new file mode 100644
index 0000000000..69e43e8cfe
--- /dev/null
+++ b/apps/web/ui/modals/social-verification-by-code-modal.tsx
@@ -0,0 +1,177 @@
+import { verifySocialAccountByCodeAction } from "@/lib/actions/partners/verify-social-account-by-code";
+import usePartnerProfile from "@/lib/swr/use-partner-profile";
+import { PlatformType } from "@dub/prisma/client";
+import { Button, buttonVariants, CopyButton, Modal } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { X } from "lucide-react";
+import { useAction } from "next-safe-action/hooks";
+import { Dispatch, ReactNode, SetStateAction } from "react";
+import { toast } from "sonner";
+
+interface SocialVerificationByCodeModalProps {
+ showSocialVerificationModal: boolean;
+ setShowSocialVerificationModal: Dispatch<SetStateAction<boolean>>;
+ platform: PlatformType;
+ handle: string;
+ verificationCode: string;
+}
+
+interface PlatformInfo {
+ name: string;
+ title: string;
+ instruction: string;
+ getProfileUrl: (handle: string) => string;
+}
+
+const PLATFORM_INFO: Record<"youtube" | "instagram", PlatformInfo> = {
+ youtube: {
+ name: "YouTube",
+ title: "Edit your YouTube channel",
+ instruction:
+ "Navigate to your channel settings and add the 6 digit code above to your channel description temporarily.",
+ getProfileUrl: (handle) => `https://www.youtube.com/@${handle}/about`,
+ },
+ instagram: {
+ name: "Instagram",
+ title: "Edit your Instagram profile",
+ instruction:
+ "Navigate to your profile settings and add the 6 digit code above to your bio temporarily.",
+ getProfileUrl: (handle) => `https://www.instagram.com/${handle}/`,
+ },
+};
+
+export function SocialVerificationByCodeModal(
+ props: SocialVerificationByCodeModalProps,
+) {
+ return (
+ <Modal
+ showModal={props.showSocialVerificationModal}
+ setShowModal={props.setShowSocialVerificationModal}
+ >
+ <SocialVerificationByCodeModalInner {...props} />
+ </Modal>
+ );
+}
+
+function SocialVerificationByCodeModalInner({
+ setShowSocialVerificationModal,
+ platform,
+ handle,
+ verificationCode,
+}: SocialVerificationByCodeModalProps) {
+ const { mutate: mutatePartner } = usePartnerProfile();
+
+ const platformInfo: PlatformInfo = PLATFORM_INFO[platform];
+ const profileUrl = platformInfo.getProfileUrl(handle);
+
+ const { executeAsync, isPending } = useAction(verifySocialAccountByCodeAction, {
+ onSuccess: async () => {
+ toast.success(`${platformInfo.name} account verified successfully!`);
+ setShowSocialVerificationModal(false);
+ await mutatePartner();
+ },
+ onError: ({ error }) => {
+ toast.error(
+ error.serverError || "Failed to verify account. Please try again.",
+ );
+ },
+ });
+
+ const handleVerify = async () => {
+ await executeAsync({
+ platform,
+ handle,
+ });
+ };
+
+ return (
+ <>
+ <div className="flex items-center justify-between border-b border-neutral-200 p-4 sm:px-6">
+ <h3 className="text-lg font-semibold leading-none">
+ Verify {platformInfo.name} account
+ </h3>
+ <button
+ type="button"
+ onClick={() => setShowSocialVerificationModal(false)}
+ className="group rounded-full p-2 text-neutral-500 transition-all duration-75 hover:bg-neutral-100 focus:outline-none active:bg-neutral-200"
+ >
+ <X className="h-5 w-5" />
+ </button>
+ </div>
+
+ <div className="flex flex-col gap-4 bg-neutral-50 p-4 sm:p-6">
+ <Step
+ stepNumber={1}
+ title="Copy the code below"
+ description="You'll use this to verify ownership of your account."
+ >
+ <div className="flex items-center justify-between gap-2 rounded-lg border border-neutral-200 bg-neutral-100 px-4 py-2.5">
+ <span className="text-content-default font-mono text-base font-medium tracking-wide">
+ {verificationCode}
+ </span>
+ <CopyButton value={verificationCode} />
+ </div>
+ </Step>
+
+ <Step
+ stepNumber={2}
+ title={platformInfo.title}
+ description={platformInfo.instruction}
+ >
+ <a
+ href={profileUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className={cn(
+ buttonVariants({ variant: "secondary" }),
+ "flex h-8 w-full items-center justify-center rounded-md border px-3 text-sm",
+ )}
+ >
+ Open {platform === "youtube" ? "channel" : "profile"}
+ </a>
+ </Step>
+
+ <Step
+ stepNumber={3}
+ title="Verify account"
+ description={`Click verify below once you've added the code to your ${platform === "youtube" ? "channel description" : "bio"}.`}
+ >
+ <Button
+ text="Verify account"
+ className="h-8 w-full px-3"
+ loading={isPending}
+ onClick={handleVerify}
+ />
+ </Step>
+ </div>
+ </>
+ );
+}
+
+function Step({
+ stepNumber,
+ title,
+ description,
+ children,
+}: {
+ stepNumber: number;
+ title: string;
+ description: string;
+ children?: ReactNode;
+}) {
+ return (
+ <div className="flex flex-col gap-4 rounded-lg border border-neutral-200 p-4">
+ <div className="text-content-default flex size-6 items-center justify-center rounded-md border border-neutral-200 bg-white p-2 text-sm font-semibold">
+ {stepNumber}
+ </div>
+ <div className="space-y-1">
+ <h4 className="text-sm font-medium text-black">{title}</h4>
+ <p className="text-content-default text-sm font-normal">
+ {description}
+ </p>
+ </div>
+ {children}
+ </div>
+ );
+}
+
diff --git a/apps/web/ui/partners/groups/design/application-form/fields/website-and-socials-field.tsx b/apps/web/ui/partners/groups/design/application-form/fields/website-and-socials-field.tsx
index 4d9462e27a..306fbefe4d 100644
--- a/apps/web/ui/partners/groups/design/application-form/fields/website-and-socials-field.tsx
+++ b/apps/web/ui/partners/groups/design/application-form/fields/website-and-socials-field.tsx
@@ -1,12 +1,9 @@
-import {
- sanitizeSocialHandle,
- sanitizeWebsite,
- SocialPlatform,
-} from "@/lib/social-utils";
+import { sanitizeSocialHandle, sanitizeWebsite } from "@/lib/social-utils";
import {
programApplicationFormSiteSchema,
programApplicationFormWebsiteAndSocialsFieldSchema,
} from "@/lib/zod/schemas/program-application-form";
+import { PlatformType } from "@dub/prisma/client";
import { cn } from "@dub/utils";
import { useCallback } from "react";
import { useFormContext } from "react-hook-form";
@@ -36,7 +33,7 @@ const Field = ({
const error = !!state.error;
const onPasteSocial = useCallback(
- (e: React.ClipboardEvent<HTMLInputElement>, platform: SocialPlatform) => {
+ (e: React.ClipboardEvent<HTMLInputElement>, platform: PlatformType) => {
const text = e.clipboardData.getData("text/plain");
const sanitized = sanitizeSocialHandle(text, platform);
diff --git a/apps/web/ui/partners/online-presence-form.tsx b/apps/web/ui/partners/online-presence-form.tsx
index d0b8098d54..d1699877c5 100644
--- a/apps/web/ui/partners/online-presence-form.tsx
+++ b/apps/web/ui/partners/online-presence-form.tsx
@@ -1,16 +1,16 @@
"use client";
import { parseActionError } from "@/lib/actions/parse-action-errors";
+import { startPartnerPlatformVerificationAction } from "@/lib/actions/partners/start-partner-platform-verification";
import { updateOnlinePresenceAction } from "@/lib/actions/partners/update-online-presence";
import { hasPermission } from "@/lib/auth/partner-users/partner-user-permissions";
-import {
- sanitizeSocialHandle,
- sanitizeWebsite,
- SocialPlatform,
-} from "@/lib/social-utils";
+import { sanitizeSocialHandle, sanitizeWebsite } from "@/lib/social-utils";
import usePartnerProfile from "@/lib/swr/use-partner-profile";
+import { PartnerPlatformProps, PartnerProps } from "@/lib/types";
import { parseUrlSchemaAllowEmpty } from "@/lib/zod/schemas/utils";
import { DomainVerificationModal } from "@/ui/modals/domain-verification-modal";
+import { SocialVerificationByCodeModal } from "@/ui/modals/social-verification-by-code-modal";
+import { PlatformType } from "@dub/prisma/client";
import {
AnimatedSizeContainer,
Button,
@@ -26,7 +26,6 @@ import {
import { getPrettyUrl, nFormatter } from "@dub/utils";
import { cn } from "@dub/utils/src/functions";
import { useAction } from "next-safe-action/hooks";
-import { useRouter } from "next/navigation";
import { forwardRef, ReactNode, useCallback, useMemo, useState } from "react";
import {
FormProvider,
@@ -40,30 +39,38 @@ import * as z from "zod/v4";
import { OnlinePresenceCard } from "./online-presence-card";
const onlinePresenceSchema = z.object({
- website: parseUrlSchemaAllowEmpty().optional(),
- youtube: z.string().optional(),
- twitter: z.string().optional(),
- linkedin: z.string().optional(),
- instagram: z.string().optional(),
- tiktok: z.string().optional(),
+ website: parseUrlSchemaAllowEmpty().nullish(),
+ youtube: z.string().nullish(),
+ twitter: z.string().nullish(),
+ linkedin: z.string().nullish(),
+ instagram: z.string().nullish(),
+ tiktok: z.string().nullish(),
});
type OnlinePresenceFormData = z.infer<typeof onlinePresenceSchema>;
interface OnlinePresenceFormProps {
variant?: "onboarding" | "settings";
- partner?: {
- email: string | null;
- website?: string | null;
- youtube?: string | null;
- twitter?: string | null;
- linkedin?: string | null;
- instagram?: string | null;
- tiktok?: string | null;
- } | null;
+ partner?: Pick<PartnerProps, "platforms"> | null;
onSubmitSuccessful?: () => void;
}
+// Helper function to get platform data from platforms array
+function getPlatformData(
+ platforms: PartnerPlatformProps[] | undefined,
+ platform: PlatformType,
+): PartnerPlatformProps | undefined {
+ return platforms?.find((p) => p.type === platform);
+}
+
+// Helper function to get identifier from platforms array
+function getPlatformIdentifier(
+ partner: OnlinePresenceFormProps["partner"],
+ platform: PlatformType,
+): string | undefined {
+ return getPlatformData(partner?.platforms, platform)?.identifier;
+}
+
/**
* Separate optional hook to allow for form management outside of the main component.
* If used, the returned form object should be passed to the main component as a prop.
@@ -73,12 +80,14 @@ export function useOnlinePresenceForm({
}: Pick<OnlinePresenceFormProps, "partner">) {
return useForm<OnlinePresenceFormData>({
defaultValues: {
- website: partner?.website ? getPrettyUrl(partner.website) : undefined,
- youtube: partner?.youtube || undefined,
- twitter: partner?.twitter || undefined,
- linkedin: partner?.linkedin || undefined,
- instagram: partner?.instagram || undefined,
- tiktok: partner?.tiktok || undefined,
+ website: getPlatformIdentifier(partner, "website")
+ ? getPrettyUrl(getPlatformIdentifier(partner, "website")!)
+ : undefined,
+ youtube: getPlatformIdentifier(partner, "youtube") || undefined,
+ twitter: getPlatformIdentifier(partner, "twitter") || undefined,
+ linkedin: getPlatformIdentifier(partner, "linkedin") || undefined,
+ instagram: getPlatformIdentifier(partner, "instagram") || undefined,
+ tiktok: getPlatformIdentifier(partner, "tiktok") || undefined,
},
});
}
@@ -109,7 +118,6 @@ export const OnlinePresenceForm = forwardRef<
const {
register,
- setError,
getValues,
handleSubmit,
reset,
@@ -118,12 +126,8 @@ export const OnlinePresenceForm = forwardRef<
} = form;
const { executeAsync } = useAction(updateOnlinePresenceAction, {
- onSuccess: (result) => {
- if (!result?.data?.success)
- setError("root.serverError", {
- message: "Failed to update online presence",
- });
- else mutate("/api/partner-profile");
+ onSuccess: async () => {
+ await mutate("/api/partner-profile");
},
onError: ({ error }) => {
toast.error(
@@ -139,7 +143,51 @@ export const OnlinePresenceForm = forwardRef<
txtRecord: string;
} | null>(null);
- const startVerification = useOAuthVerification(variant);
+ const [socialVerificationData, setSocialVerificationData] = useState<{
+ platform: PlatformType;
+ handle: string;
+ verificationCode: string;
+ } | null>(null);
+
+ const {
+ executeAsync: startSocialVerification,
+ isPending: isStartingSocialVerification,
+ } = useAction(startPartnerPlatformVerificationAction, {
+ onSuccess: ({ input, data }) => {
+ if (!input || !data) {
+ return;
+ }
+
+ // For website verification (TXT record)
+ if (data.type === "txt_record") {
+ const websiteUrl = input.handle.startsWith("http")
+ ? input.handle
+ : `https://${input.handle}`;
+
+ setDomainVerificationData({
+ domain: new URL(websiteUrl).hostname,
+ txtRecord: data.websiteTxtRecord,
+ });
+ }
+
+ // For OAuth flow
+ else if (data.type === "oauth") {
+ window.location.href = data.oauthUrl;
+ }
+
+ // For verification code flow
+ else if (data.type === "verification_code") {
+ setSocialVerificationData({
+ platform: input.platform,
+ handle: input.handle,
+ verificationCode: data.verificationCode,
+ });
+ }
+ },
+ onError: ({ error }) => {
+ toast.error(parseActionError(error, "Failed to start verification."));
+ },
+ });
const onPasteWebsite = useCallback(
(e: React.ClipboardEvent<HTMLInputElement>) => {
@@ -155,7 +203,7 @@ export const OnlinePresenceForm = forwardRef<
);
const onPasteSocial = useCallback(
- (e: React.ClipboardEvent<HTMLInputElement>, platform: SocialPlatform) => {
+ (e: React.ClipboardEvent<HTMLInputElement>, platform: PlatformType) => {
const text = e.clipboardData.getData("text/plain");
const sanitized = sanitizeSocialHandle(text, platform);
@@ -169,19 +217,35 @@ export const OnlinePresenceForm = forwardRef<
return (
<>
- <DomainVerificationModal
- showDomainVerificationModal={domainVerificationData !== null}
- setShowDomainVerificationModal={() => setDomainVerificationData(null)}
- domain={domainVerificationData?.domain || ""}
- txtRecord={domainVerificationData?.txtRecord || ""}
- />
+ {domainVerificationData && (
+ <DomainVerificationModal
+ domain={domainVerificationData.domain}
+ txtRecord={domainVerificationData.txtRecord}
+ showDomainVerificationModal={domainVerificationData !== null}
+ setShowDomainVerificationModal={() =>
+ setDomainVerificationData(null)
+ }
+ />
+ )}
+
+ {socialVerificationData && (
+ <SocialVerificationByCodeModal
+ platform={socialVerificationData.platform}
+ handle={socialVerificationData.handle}
+ verificationCode={socialVerificationData.verificationCode}
+ showSocialVerificationModal={socialVerificationData !== null}
+ setShowSocialVerificationModal={(show) => {
+ if (!show) setSocialVerificationData(null);
+ }}
+ />
+ )}
+
<FormProvider {...form}>
<form
ref={ref}
onSubmit={handleSubmit(async (data) => {
const result = await executeAsync(data);
-
- if (result?.data?.success) onSubmitSuccessful?.();
+ if (result) onSubmitSuccessful?.();
})}
>
<div
@@ -193,35 +257,20 @@ export const OnlinePresenceForm = forwardRef<
<FormRow
label="Website"
property="website"
- verifiedAtField="websiteVerifiedAt"
icon={Globe}
disabled={disabled}
onVerifyClick={async () => {
- try {
- const result =
- await updateOnlinePresenceAction(getValues());
-
- if (
- !result?.data?.website ||
- !result?.data?.websiteTxtRecord
- ) {
- throw new Error(
- "Missing website or TXT record in update result",
- );
- }
-
- setDomainVerificationData({
- domain: new URL(result.data.website).hostname,
- txtRecord: result.data.websiteTxtRecord,
- });
+ const website = getValues("website");
- mutate("/api/partner-profile");
- } catch (e) {
- toast.error("Failed to start website verification");
- console.error("Failed to start website verification", e);
+ if (website) {
+ await startSocialVerification({
+ platform: "website",
+ handle: website,
+ source: variant,
+ });
}
- return false;
+ return isStartingSocialVerification;
}}
input={
<input
@@ -247,13 +296,21 @@ export const OnlinePresenceForm = forwardRef<
label="YouTube"
property="youtube"
prefix="@"
- verifiedAtField="youtubeVerifiedAt"
icon={YouTube}
disabled={disabled}
- onVerifyClick={() =>
- startVerification("youtube", getValues("youtube"))
- }
- verifyDisabledTooltip="YouTube verification is coming soon."
+ onVerifyClick={async () => {
+ const handle = getValues("youtube");
+
+ if (handle) {
+ await startSocialVerification({
+ platform: "youtube",
+ handle,
+ source: variant,
+ });
+ }
+
+ return isStartingSocialVerification;
+ }}
input={
<div className="flex rounded-md">
<span className="inline-flex items-center rounded-l-md border border-r-0 border-neutral-300 bg-neutral-50 px-3 text-neutral-500 sm:text-sm">
@@ -286,12 +343,21 @@ export const OnlinePresenceForm = forwardRef<
label="X/Twitter"
property="twitter"
prefix="@"
- verifiedAtField="twitterVerifiedAt"
icon={Twitter}
disabled={disabled}
- onVerifyClick={() =>
- startVerification("twitter", getValues("twitter"))
- }
+ onVerifyClick={async () => {
+ const handle = getValues("twitter");
+
+ if (handle) {
+ await startSocialVerification({
+ platform: "twitter",
+ handle,
+ source: variant,
+ });
+ }
+
+ return isStartingSocialVerification;
+ }}
input={
<div className="flex rounded-md">
<span className="inline-flex items-center rounded-l-md border border-r-0 border-neutral-300 bg-neutral-50 px-3 text-neutral-500 sm:text-sm">
@@ -321,13 +387,22 @@ export const OnlinePresenceForm = forwardRef<
label="LinkedIn"
property="linkedin"
prefix="in/"
- verifiedAtField="linkedinVerifiedAt"
icon={LinkedIn}
disabled={disabled}
- onVerifyClick={() =>
- startVerification("linkedin", getValues("linkedin"))
- }
verifyDisabledTooltip="LinkedIn verification is coming soon."
+ onVerifyClick={async () => {
+ const handle = getValues("linkedin");
+
+ if (handle) {
+ await startSocialVerification({
+ platform: "linkedin",
+ handle,
+ source: variant,
+ });
+ }
+
+ return isStartingSocialVerification;
+ }}
input={
<div className="flex rounded-md">
<span className="inline-flex items-center rounded-l-md border border-r-0 border-neutral-300 bg-neutral-50 px-3 text-neutral-500 sm:text-sm">
@@ -357,13 +432,21 @@ export const OnlinePresenceForm = forwardRef<
label="Instagram"
property="instagram"
prefix="@"
- verifiedAtField="instagramVerifiedAt"
icon={Instagram}
disabled={disabled}
- onVerifyClick={() =>
- startVerification("instagram", getValues("instagram"))
- }
- verifyDisabledTooltip="Instagram verification is coming soon."
+ onVerifyClick={async () => {
+ const handle = getValues("instagram");
+
+ if (handle) {
+ await startSocialVerification({
+ platform: "instagram",
+ handle,
+ source: variant,
+ });
+ }
+
+ return isStartingSocialVerification;
+ }}
input={
<div className="flex rounded-md">
<span className="inline-flex items-center rounded-l-md border border-r-0 border-neutral-300 bg-neutral-50 px-3 text-neutral-500 sm:text-sm">
@@ -393,12 +476,21 @@ export const OnlinePresenceForm = forwardRef<
label="TikTok"
property="tiktok"
prefix="@"
- verifiedAtField="tiktokVerifiedAt"
icon={TikTok}
disabled={disabled}
- onVerifyClick={() =>
- startVerification("tiktok", getValues("tiktok"))
- }
+ onVerifyClick={async () => {
+ const handle = getValues("tiktok");
+
+ if (handle) {
+ await startSocialVerification({
+ platform: "tiktok",
+ handle,
+ source: variant,
+ });
+ }
+
+ return isStartingSocialVerification;
+ }}
input={
<div className="flex rounded-md">
<span className="inline-flex items-center rounded-l-md border border-r-0 border-neutral-300 bg-neutral-50 px-3 text-neutral-500 sm:text-sm">
@@ -444,44 +536,10 @@ export const OnlinePresenceForm = forwardRef<
},
);
-function useOAuthVerification(source: "onboarding" | "settings") {
- const router = useRouter();
-
- return useCallback(
- async (provider: string, value?: string) => {
- if (!value) return false;
-
- try {
- const result = await updateOnlinePresenceAction({
- [provider]: value,
- source,
- });
-
- if (
- result?.data?.success &&
- result?.data?.verificationUrls?.[provider]
- ) {
- window.location.href = result.data.verificationUrls[provider];
- }
-
- return true;
- } catch (e) {
- toast.error("Failed to start verification");
- console.error("Failed to start verification", e);
- }
-
- return false;
- },
- [source, router],
- );
-}
-
function useVerifiedState({
property,
- verifiedAtField,
}: {
property: keyof OnlinePresenceFormData;
- verifiedAtField: string;
}) {
const { partner: partnerProfile } = usePartnerProfile();
@@ -492,12 +550,26 @@ function useVerifiedState({
const loading = !partnerProfile && isValid;
+ // Map form property to PlatformType enum
+ const platformMap: Record<keyof OnlinePresenceFormData, PlatformType> = {
+ website: "website",
+ youtube: "youtube",
+ twitter: "twitter",
+ linkedin: "linkedin",
+ instagram: "instagram",
+ tiktok: "tiktok",
+ };
+
+ const platform = platformMap[property];
+ const currentHandle = getPlatformIdentifier(partnerProfile, platform);
+
const noChange =
property === "website"
- ? getPrettyUrl(partnerProfile?.[property] ?? "") === getPrettyUrl(value)
- : partnerProfile?.[property] === value;
+ ? getPrettyUrl(currentHandle ?? "") === getPrettyUrl(value ?? "")
+ : currentHandle === value;
- const isVerified = noChange && Boolean(partnerProfile?.[verifiedAtField]);
+ const platformData = getPlatformData(partnerProfile?.platforms, platform);
+ const isVerified = noChange && Boolean(platformData?.verifiedAt);
return {
isVerified,
@@ -507,14 +579,12 @@ function useVerifiedState({
function VerifyButton({
property,
- verifiedAtField,
icon: Icon,
onClick,
disabledTooltip,
disabled: formDisabled = false,
}: {
property: keyof OnlinePresenceFormData;
- verifiedAtField: string;
icon: Icon;
onClick: () => Promise<boolean>;
disabledTooltip?: string;
@@ -525,7 +595,6 @@ function VerifyButton({
const { isVerified, loading } = useVerifiedState({
property,
- verifiedAtField,
});
const [isSaving, setIsSaving] = useState(false);
@@ -568,7 +637,6 @@ function FormRow({
input,
property,
prefix,
- verifiedAtField,
icon: Icon,
onVerifyClick,
verifyDisabledTooltip,
@@ -580,7 +648,6 @@ function FormRow({
property: keyof OnlinePresenceFormData;
prefix?: string;
- verifiedAtField: string;
icon: Icon;
onVerifyClick: () => Promise<boolean>;
verifyDisabledTooltip?: string;
@@ -591,17 +658,26 @@ function FormRow({
const { control, setValue } = useFormContext<OnlinePresenceFormData>();
const value = useWatch({ control, name: property });
- const { isVerified } = useVerifiedState({ property, verifiedAtField });
+ const { isVerified } = useVerifiedState({ property });
const info = useMemo(() => {
if (partner && property === "youtube" && isVerified) {
+ // Type assertion for platforms array that exists at runtime but not in type
+ const partnerWithPlatforms = partner as typeof partner & {
+ platforms?: PartnerPlatformProps[];
+ };
+ const youtubePlatform = getPlatformData(
+ partnerWithPlatforms.platforms,
+ "youtube",
+ );
+ const subscribers = youtubePlatform?.subscribers ?? 0;
+ const views = youtubePlatform?.views ?? 0;
+
return [
- partner.youtubeSubscriberCount && partner.youtubeSubscriberCount > 0
- ? `${nFormatter(partner.youtubeSubscriberCount)} subscribers`
- : null,
- partner.youtubeViewCount && partner.youtubeViewCount > 0
- ? `${nFormatter(partner.youtubeViewCount)} views`
+ subscribers > 0
+ ? `${nFormatter(Number(subscribers))} subscribers`
: null,
+ views > 0 ? `${nFormatter(Number(views))} views` : null,
].filter(Boolean) as string[];
}
return null;
@@ -631,7 +707,7 @@ function FormRow({
value={value ?? ""}
verified
info={info ?? undefined}
- onRemove={() => setValue(property, "", { shouldDirty: true })}
+ onRemove={() => setValue(property, null, { shouldDirty: true })}
/>
</div>
) : (
@@ -648,7 +724,6 @@ function FormRow({
{input}
<VerifyButton
property={property}
- verifiedAtField={verifiedAtField}
icon={Icon}
onClick={onVerifyClick}
disabledTooltip={verifyDisabledTooltip}
diff --git a/apps/web/ui/partners/online-presence-summary.tsx b/apps/web/ui/partners/online-presence-summary.tsx
index 51e9b08f25..c84eb321b0 100644
--- a/apps/web/ui/partners/online-presence-summary.tsx
+++ b/apps/web/ui/partners/online-presence-summary.tsx
@@ -1,30 +1,41 @@
-import {
- ONLINE_PRESENCE_FIELDS,
- PartnerOnlinePresenceFields,
-} from "@/lib/partners/online-presence";
-import { EnrolledPartnerExtendedProps } from "@/lib/types";
+import { ONLINE_PRESENCE_FIELDS } from "@/lib/partners/online-presence";
+import { PartnerPlatformProps } from "@/lib/types";
import { cn } from "@dub/utils";
import { Fragment } from "react";
import { OnlinePresenceCard } from "./online-presence-card";
export function OnlinePresenceSummary({
- partner,
+ platforms,
showLabels = true,
className,
emptyClassName,
}: {
- partner: Pick<EnrolledPartnerExtendedProps, PartnerOnlinePresenceFields>;
+ platforms: PartnerPlatformProps[] | undefined;
showLabels?: boolean;
className?: string;
emptyClassName?: string;
}) {
+ if (!platforms || platforms.length === 0) {
+ return (
+ <div
+ className={cn(
+ "text-sm italic text-neutral-400",
+ className,
+ emptyClassName,
+ )}
+ >
+ No online presence provided
+ </div>
+ );
+ }
+
const fieldData = ONLINE_PRESENCE_FIELDS.map((field) => ({
label: field.label,
icon: field.icon,
- ...field.data(partner),
+ ...field.data(platforms),
})).filter((field) => field.value && field.href);
- return fieldData.length ? (
+ return (
<div
className={cn(
"grid items-center gap-x-4 gap-y-5 text-sm md:gap-x-16",
@@ -51,15 +62,5 @@ export function OnlinePresenceSummary({
);
})}
</div>
- ) : (
- <div
- className={cn(
- "text-sm italic text-neutral-400",
- className,
- emptyClassName,
- )}
- >
- No online presence provided
- </div>
);
}
diff --git a/apps/web/ui/partners/partner-about.tsx b/apps/web/ui/partners/partner-about.tsx
index 254b1e8ac9..ceda5f5da7 100644
--- a/apps/web/ui/partners/partner-about.tsx
+++ b/apps/web/ui/partners/partner-about.tsx
@@ -21,20 +21,7 @@ export function PartnerAbout({
| "salesChannels"
| "preferredEarningStructures"
| "monthlyTraffic"
- | "website"
- | "websiteVerifiedAt"
- | "youtube"
- | "youtubeSubscriberCount"
- | "youtubeVerifiedAt"
- | "youtubeViewCount"
- | "twitter"
- | "twitterVerifiedAt"
- | "linkedin"
- | "linkedinVerifiedAt"
- | "instagram"
- | "instagramVerifiedAt"
- | "tiktok"
- | "tiktokVerifiedAt"
+ | "platforms"
>;
error?: any;
}) {
@@ -58,7 +45,7 @@ export function PartnerAbout({
Website and socials
</h3>
<OnlinePresenceSummary
- partner={partner}
+ platforms={partner.platforms}
showLabels={false}
className="gap-y-2"
/>
diff --git a/apps/web/ui/partners/partner-profile-sheet.tsx b/apps/web/ui/partners/partner-profile-sheet.tsx
index 4bede4eaab..d1ca8e3d49 100644
--- a/apps/web/ui/partners/partner-profile-sheet.tsx
+++ b/apps/web/ui/partners/partner-profile-sheet.tsx
@@ -48,6 +48,7 @@ function PartnerProfileSheetContent({ partner }: PartnerProfileSheetProps) {
</div>
);
}
+
export function PartnerProfileSheet({
isOpen,
nested,
diff --git a/apps/web/ui/partners/partner-social-column.tsx b/apps/web/ui/partners/partner-social-column.tsx
index 1977619d20..a0af68f06a 100644
--- a/apps/web/ui/partners/partner-social-column.tsx
+++ b/apps/web/ui/partners/partner-social-column.tsx
@@ -1,18 +1,37 @@
+import { PartnerPlatformProps } from "@/lib/types";
+import { PlatformType } from "@dub/prisma/client";
import { BadgeCheck2Fill, Tooltip } from "@dub/ui";
+import { getDomainWithoutWWW } from "@dub/utils";
+
+const PLATFORMS_WITH_AT: PlatformType[] = [
+ "youtube",
+ "twitter",
+ "instagram",
+ "tiktok",
+];
export function PartnerSocialColumn({
- at,
- value,
- verified,
+ platform,
+ platformName,
}: {
- at?: boolean;
- value: string;
- verified: boolean;
+ platform: PartnerPlatformProps | null | undefined;
+ platformName: PlatformType;
}) {
- return value ? (
+ if (!platform?.identifier) {
+ return "-";
+ }
+
+ const needsAt = PLATFORMS_WITH_AT.includes(platformName);
+ const value =
+ platformName === "website"
+ ? getDomainWithoutWWW(platform.identifier) ?? "-"
+ : platform.identifier;
+ const verified = !!platform.verifiedAt;
+
+ return (
<div className="flex items-center gap-2">
<span className="min-w-0 truncate">
- {at && "@"}
+ {needsAt && "@"}
{value}
</span>
{verified && (
@@ -23,7 +42,5 @@ export function PartnerSocialColumn({
</Tooltip>
)}
</div>
- ) : (
- "-"
);
}
diff --git a/packages/prisma/client.ts b/packages/prisma/client.ts
index f88ab9bc5c..d771c2cb20 100644
--- a/packages/prisma/client.ts
+++ b/packages/prisma/client.ts
@@ -26,6 +26,7 @@ export {
PartnerRole,
PayoutMode,
PayoutStatus,
+ PlatformType,
PreferredEarningStructure,
Prisma,
ProgramEnrollmentStatus,
diff --git a/packages/prisma/schema/partner.prisma b/packages/prisma/schema/partner.prisma
index e0140cf8e4..cf8a9ac97c 100644
--- a/packages/prisma/schema/partner.prisma
+++ b/packages/prisma/schema/partner.prisma
@@ -82,6 +82,7 @@ model Partner {
fraudEventGroups FraudEventGroup[]
fraudEvents FraudEvent[]
partnerRewinds PartnerRewind[]
+ platforms PartnerPlatform[]
@@index(country)
@@index(discoverableAt)
diff --git a/packages/prisma/schema/platform.prisma b/packages/prisma/schema/platform.prisma
new file mode 100644
index 0000000000..379839b440
--- /dev/null
+++ b/packages/prisma/schema/platform.prisma
@@ -0,0 +1,28 @@
+enum PlatformType {
+ website
+ youtube
+ twitter
+ linkedin
+ instagram
+ tiktok
+}
+
+model PartnerPlatform {
+ id String @id @default(cuid())
+ partnerId String
+ type PlatformType
+ identifier String // The unique identifier for the platform (e.g., username for social platforms, domain for websites)
+ platformId String? // Platform-specific immutable ID (e.g., YouTube channel ID)
+ verifiedAt DateTime?
+ subscribers BigInt @default(0) // Subscribers/followers for social platforms, also for newsletter subscribers
+ posts BigInt @default(0)
+ views BigInt @default(0) // Video views for YouTube, impressions for social platforms, pageviews for websites
+ metadata Json?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ partner Partner @relation(fields: [partnerId], references: [id], onDelete: Cascade)
+
+ @@unique([partnerId, type])
+ @@index(type)
+}