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.

1.3 KB
Raw Blame
"use server";

import { prisma } from "@/lib/prisma";
import * as z from "zod/v4";
import { OAUTH_CONFIG } from "../api/oauth/constants";
import { createToken } from "../api/oauth/utils";
import { hashToken } from "../auth";
import { authActionClient } from "./safe-action";
import { throwIfNoPermission } from "./throw-if-no-permission";

const schema = z.object({
  workspaceId: z.string(),
  appId: z.string(),
});

// Generate a new client secret for an integration
export const generateClientSecret = authActionClient
  .inputSchema(schema)
  .action(async ({ ctx, parsedInput }) => {
    const { workspace } = ctx;
    const { appId } = parsedInput;

    throwIfNoPermission({
      role: workspace.role,
      requiredPermissions: ["oauth_apps.write"],
    });

    await prisma.integration.findFirstOrThrow({
      where: {
        id: appId,
        projectId: workspace.id,
      },
    });

    const clientSecret = createToken({
      length: OAUTH_CONFIG.CLIENT_SECRET_LENGTH,
      prefix: OAUTH_CONFIG.CLIENT_SECRET_PREFIX,
    });

    await prisma.oAuthApp.update({
      where: {
        integrationId: appId,
      },
      data: {
        hashedClientSecret: await hashToken(clientSecret),
        partialClientSecret: `dub_app_secret_****${clientSecret.slice(-8)}`,
      },
    });

    return { clientSecret };
  });