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.

Encrypt credentials (#3813)

Kiran K9046d84a298e
diff --git a/apps/web/.env.example b/apps/web/.env.example
index d8d5320c14..81f7494510 100644
--- a/apps/web/.env.example
+++ b/apps/web/.env.example
@@ -6,9 +6,15 @@ NEXT_PUBLIC_APP_NAME=Dub
NEXT_PUBLIC_APP_DOMAIN=dub.co
NEXT_PUBLIC_APP_SHORT_DOMAIN=dub.sh
-# Generate a random secret here: https://generate-secret.vercel.app/32
+# Generate secrets with: node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
NEXTAUTH_SECRET=
NEXTAUTH_URL=http://localhost:8888 # (only needed for localhost)
+# Secret for Vercel cron jobs (https://vercel.com/docs/cron-jobs/manage-cron-jobs#securing-cron-jobs)
+CRON_SECRET=
+# Encryption key (AES-256-GCM) for encrypting sensitive data in the database
+ENCRYPTION_KEY=
+# Email unsubscribe token secret (optional, falls back to NEXTAUTH_SECRET)
+UNSUBSCRIBE_TOKEN_SECRET=
# MySQL Database via Planetscale
# Get your MySQL Database URL here: https://planetscale.com/docs/tutorials/connect-nodejs-app
@@ -50,9 +56,6 @@ 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 ######
###############################
@@ -140,9 +143,6 @@ PLAIN_WEBHOOK_SECRET=
# For the official Dub app
NEXT_PUBLIC_IS_DUB=
-# For cron jobs
-CRON_SECRET=
-
# For storing vector embeddings (/api/support/chat)
UPSTASH_VECTOR_REST_URL=
UPSTASH_VECTOR_REST_TOKEN=
diff --git a/apps/web/app/(ee)/api/hubspot/callback/route.ts b/apps/web/app/(ee)/api/hubspot/callback/route.ts
index 63437ad362..1fd2d6bc16 100644
--- a/apps/web/app/(ee)/api/hubspot/callback/route.ts
+++ b/apps/web/app/(ee)/api/hubspot/callback/route.ts
@@ -1,5 +1,6 @@
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { getSession } from "@/lib/auth";
+import { encrypt } from "@/lib/encryption";
import { HubSpotApi } from "@/lib/integrations/hubspot/api";
import { HUBSPOT_DUB_CONTACT_PROPERTIES } from "@/lib/integrations/hubspot/constants";
import { hubSpotOAuthProvider } from "@/lib/integrations/hubspot/oauth";
@@ -86,6 +87,8 @@ export const GET = async (req: Request) => {
const credentials = {
...token,
created_at: Date.now(),
+ access_token: encrypt(token.access_token),
+ refresh_token: encrypt(token.refresh_token),
};
const installedIntegration = await installIntegration({
@@ -97,7 +100,7 @@ export const GET = async (req: Request) => {
if (installedIntegration) {
const hubSpotApi = new HubSpotApi({
- token: credentials.access_token,
+ token: token.access_token,
});
waitUntil(
diff --git a/apps/web/app/(ee)/api/shopify/integration/callback/route.ts b/apps/web/app/(ee)/api/shopify/integration/callback/route.ts
index 7cba9c4fe5..71851621e9 100644
--- a/apps/web/app/(ee)/api/shopify/integration/callback/route.ts
+++ b/apps/web/app/(ee)/api/shopify/integration/callback/route.ts
@@ -1,6 +1,7 @@
import { DubApiError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
+import { encrypt } from "@/lib/encryption";
import { installIntegration } from "@/lib/integrations/install";
import { prisma } from "@dub/prisma";
import { SHOPIFY_INTEGRATION_ID } from "@dub/utils";
@@ -46,7 +47,7 @@ export const PATCH = withWorkspace(
workspaceId: workspace.id,
integrationId: SHOPIFY_INTEGRATION_ID,
credentials: {
- accessToken: body.accessToken,
+ accessToken: encrypt(body.accessToken),
scope: body.scope,
},
});
diff --git a/apps/web/app/api/slack/callback/route.ts b/apps/web/app/api/slack/callback/route.ts
index 44dbb76f0b..582ef529af 100644
--- a/apps/web/app/api/slack/callback/route.ts
+++ b/apps/web/app/api/slack/callback/route.ts
@@ -1,5 +1,6 @@
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { getSession } from "@/lib/auth";
+import { encrypt } from "@/lib/encryption";
import { installIntegration } from "@/lib/integrations/install";
import { slackOAuthProvider } from "@/lib/integrations/slack/oauth";
import { SlackAuthToken } from "@/lib/integrations/types";
@@ -67,7 +68,7 @@ export const GET = async (req: Request) => {
appId: token.app_id,
botUserId: token.bot_user_id,
scope: token.scope,
- accessToken: token.access_token,
+ accessToken: encrypt(token.access_token),
tokenType: token.token_type,
authUser: token.authed_user,
team: token.team,
diff --git a/apps/web/lib/discounts/discount-provider-shopify.ts b/apps/web/lib/discounts/discount-provider-shopify.ts
index 52c69d1e80..6938154d6f 100644
--- a/apps/web/lib/discounts/discount-provider-shopify.ts
+++ b/apps/web/lib/discounts/discount-provider-shopify.ts
@@ -1,3 +1,4 @@
+import { decryptOrPassthrough } from "@/lib/encryption";
import { prisma } from "@dub/prisma";
import { Discount, Project } from "@dub/prisma/client";
import { SHOPIFY_INTEGRATION_ID, nanoid } from "@dub/utils";
@@ -70,7 +71,12 @@ async function requireInstalledIntegration(
return {
...installation,
- credentials,
+ credentials: {
+ ...credentials,
+ accessToken: credentials.accessToken
+ ? decryptOrPassthrough(credentials.accessToken)
+ : credentials.accessToken,
+ },
};
}
diff --git a/apps/web/lib/encryption.ts b/apps/web/lib/encryption.ts
new file mode 100644
index 0000000000..524bc72904
--- /dev/null
+++ b/apps/web/lib/encryption.ts
@@ -0,0 +1,63 @@
+// @ts-nocheck — Node `Buffer` is valid for `createCipheriv`; local @types/node uses strict ArrayBuffer branding.
+import crypto from "node:crypto";
+
+const ALGORITHM = "aes-256-gcm";
+const IV_LENGTH = 12;
+
+function loadEncryptionKey(): Buffer {
+ const keyEnv = process.env.ENCRYPTION_KEY;
+ if (!keyEnv) {
+ throw new Error("ENCRYPTION_KEY is not set");
+ }
+
+ const key = Buffer.from(keyEnv, "base64");
+ if (key.length !== 32) {
+ throw new Error("ENCRYPTION_KEY must be 32 bytes (base64-encoded)");
+ }
+
+ return key;
+}
+
+// AES-256-GCM encrypt.
+export function encrypt(plaintext: string) {
+ const key = loadEncryptionKey();
+ const iv = crypto.randomBytes(IV_LENGTH);
+ const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
+ const encrypted = Buffer.concat([
+ cipher.update(plaintext, "utf8"),
+ cipher.final(),
+ ]);
+
+ const authTag = cipher.getAuthTag();
+
+ return Buffer.concat([iv, authTag, encrypted]).toString("base64");
+}
+
+// AES-256-GCM decrypt. Throws on any failure (bad key, tampered ciphertext, plaintext input).
+export function decrypt(payload: string) {
+ const key = loadEncryptionKey();
+ const data = Buffer.from(payload, "base64");
+ const iv = data.subarray(0, IV_LENGTH);
+ const authTag = data.subarray(IV_LENGTH, IV_LENGTH + 16);
+ const encrypted = data.subarray(IV_LENGTH + 16);
+ const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
+
+ decipher.setAuthTag(authTag);
+
+ return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString(
+ "utf8",
+ );
+}
+
+// Tolerant variant: successful decrypt(payload) returns plaintext; if decrypt throws, this returns the input unchanged.
+// Should be removed after migration is complete.
+export function decryptOrPassthrough(payload: string) {
+ try {
+ return decrypt(payload);
+ } catch {
+ console.warn(
+ "[decryptOrPassthrough] decrypt failed, returning input as plaintext",
+ );
+ return payload;
+ }
+}
diff --git a/apps/web/lib/integrations/hubspot/api.ts b/apps/web/lib/integrations/hubspot/api.ts
index e68c235415..6893964685 100644
--- a/apps/web/lib/integrations/hubspot/api.ts
+++ b/apps/web/lib/integrations/hubspot/api.ts
@@ -1,3 +1,4 @@
+import { prettyPrint } from "@dub/utils";
import { hubSpotContactSchema, hubSpotDealSchema } from "./schema";
type FetchOptions = Omit<RequestInit, "body"> & {
@@ -36,7 +37,7 @@ export class HubSpotApi {
if (process.env.NODE_ENV === "development") {
console.log("[HubSpot] API response", {
url,
- result,
+ result: prettyPrint(result),
});
}
diff --git a/apps/web/lib/integrations/hubspot/oauth.ts b/apps/web/lib/integrations/hubspot/oauth.ts
index 8738985e9c..34a7d95b01 100644
--- a/apps/web/lib/integrations/hubspot/oauth.ts
+++ b/apps/web/lib/integrations/hubspot/oauth.ts
@@ -1,3 +1,4 @@
+import { decryptOrPassthrough, encrypt } from "@/lib/encryption";
import { prisma } from "@dub/prisma";
import { InstalledIntegration } from "@dub/prisma/client";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
@@ -15,7 +16,13 @@ class HubSpotOAuthProvider extends OAuthProvider<
async refreshTokenForInstallation(
installation: InstalledIntegration,
): Promise<HubSpotAuthToken> {
- const token = hubSpotAuthTokenSchema.parse(installation.credentials);
+ let token = hubSpotAuthTokenSchema.parse(installation.credentials);
+
+ token = {
+ ...token,
+ access_token: decryptOrPassthrough(token.access_token),
+ refresh_token: decryptOrPassthrough(token.refresh_token),
+ };
if (this.isTokenValid(token)) {
return token;
@@ -33,7 +40,11 @@ class HubSpotOAuthProvider extends OAuthProvider<
id: installation.id,
},
data: {
- credentials,
+ credentials: {
+ ...credentials,
+ access_token: encrypt(credentials.access_token),
+ refresh_token: encrypt(credentials.refresh_token),
+ },
},
});
diff --git a/apps/web/lib/integrations/segment/install.ts b/apps/web/lib/integrations/segment/install.ts
index b114a62f35..7df4384e83 100644
--- a/apps/web/lib/integrations/segment/install.ts
+++ b/apps/web/lib/integrations/segment/install.ts
@@ -1,20 +1,21 @@
"use server";
import { authActionClient } from "@/lib/actions/safe-action";
+import { encrypt } from "@/lib/encryption";
import { createWebhook } from "@/lib/webhook/create-webhook";
import { WebhookReceiver } from "@dub/prisma/client";
import { SEGMENT_INTEGRATION_ID } from "@dub/utils";
import { revalidatePath } from "next/cache";
import * as z from "zod/v4";
import { installIntegration } from "../install";
+import { segmentCredentialsSchema } from "./schema";
-const schema = z.object({
- writeKey: z.string().min(1).max(40),
+const inputSchema = segmentCredentialsSchema.extend({
workspaceId: z.string(),
});
export const installSegmentAction = authActionClient
- .inputSchema(schema)
+ .inputSchema(inputSchema)
.action(async ({ parsedInput, ctx }) => {
const { workspace, user } = ctx;
const { writeKey } = parsedInput;
@@ -24,7 +25,7 @@ export const installSegmentAction = authActionClient
userId: user.id,
workspaceId: workspace.id,
credentials: {
- writeKey,
+ writeKey: encrypt(writeKey),
},
});
diff --git a/apps/web/lib/integrations/segment/schema.ts b/apps/web/lib/integrations/segment/schema.ts
new file mode 100644
index 0000000000..38891e2dfe
--- /dev/null
+++ b/apps/web/lib/integrations/segment/schema.ts
@@ -0,0 +1,5 @@
+import * as z from "zod/v4";
+
+export const segmentCredentialsSchema = z.object({
+ writeKey: z.string().min(1).max(255),
+});
diff --git a/apps/web/lib/integrations/slack/commands.ts b/apps/web/lib/integrations/slack/commands.ts
index e1d52959dd..709920e95d 100644
--- a/apps/web/lib/integrations/slack/commands.ts
+++ b/apps/web/lib/integrations/slack/commands.ts
@@ -1,4 +1,5 @@
import { createLink, processLink } from "@/lib/api/links";
+import { decryptOrPassthrough } from "@/lib/encryption";
import { WorkspaceProps } from "@/lib/types";
import { createLinkBodySchema } from "@/lib/zod/schemas/links";
import { prisma } from "@dub/prisma";
@@ -77,7 +78,10 @@ export const handleSlashCommand = async (req: Request) => {
const credentials = installation.credentials as SlackAuthToken;
const slackUser = await findSlackUser({
userId: data.user_id,
- credentials,
+ credentials: {
+ ...credentials,
+ accessToken: decryptOrPassthrough(credentials.accessToken),
+ },
});
const dubUser = await prisma.user.findUnique({
@@ -116,7 +120,7 @@ export const handleSlashCommand = async (req: Request) => {
})) as WorkspaceProps;
if (data.command === "/shorten") {
- return createShortLink({
+ return await createShortLink({
data,
workspace,
user: dubUser,
diff --git a/apps/web/lib/integrations/slack/oauth.ts b/apps/web/lib/integrations/slack/oauth.ts
index e98611a05a..13010981f3 100644
--- a/apps/web/lib/integrations/slack/oauth.ts
+++ b/apps/web/lib/integrations/slack/oauth.ts
@@ -1,4 +1,5 @@
import { DubApiError } from "@/lib/api/errors";
+import { decryptOrPassthrough } from "@/lib/encryption";
import { InstalledIntegration } from "@dub/prisma/client";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { OAuthProvider, OAuthProviderConfig } from "../oauth-provider";
@@ -19,7 +20,7 @@ class SlackOAuthProvider extends OAuthProvider<typeof slackAuthTokenSchema> {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
- token: credentials.accessToken,
+ token: decryptOrPassthrough(credentials.accessToken),
client_id: process.env.SLACK_CLIENT_ID!,
client_secret: process.env.SLACK_CLIENT_SECRET!,
}),
diff --git a/apps/web/scripts/migrations/backfill-encrypt-integration-credentials.ts b/apps/web/scripts/migrations/backfill-encrypt-integration-credentials.ts
new file mode 100644
index 0000000000..07a047d943
--- /dev/null
+++ b/apps/web/scripts/migrations/backfill-encrypt-integration-credentials.ts
@@ -0,0 +1,141 @@
+import "dotenv-flow/config";
+
+import { decrypt, encrypt } from "@/lib/encryption";
+import { prisma } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
+import {
+ HUBSPOT_INTEGRATION_ID,
+ SEGMENT_INTEGRATION_ID,
+ SHOPIFY_INTEGRATION_ID,
+ SLACK_INTEGRATION_ID,
+} from "@dub/utils";
+import * as z from "zod/v4";
+
+// Encrypts plaintext credential fields on existing InstalledIntegration rows.
+// Idempotent: a field that already round-trips through decrypt() is left alone.
+function isAlreadyEncrypted(value: string) {
+ if (typeof value !== "string" || value.length === 0) {
+ return false;
+ }
+
+ try {
+ decrypt(value);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+async function main() {
+ const installations = await prisma.installedIntegration.findMany({
+ where: {
+ integrationId: {
+ in: [
+ SLACK_INTEGRATION_ID,
+ HUBSPOT_INTEGRATION_ID,
+ SEGMENT_INTEGRATION_ID,
+ SHOPIFY_INTEGRATION_ID,
+ ],
+ },
+ credentials: {
+ not: Prisma.DbNull,
+ },
+ },
+ select: {
+ id: true,
+ integrationId: true,
+ credentials: true,
+ },
+ });
+
+ if (installations.length === 0) {
+ console.log("No installations found");
+ return;
+ }
+
+ for (const installation of installations) {
+ const credentials = installation.credentials as Record<string, string>;
+
+ if (!credentials || typeof credentials !== "object") {
+ continue;
+ }
+
+ let encryptedCredentials: Record<string, any> | null = null;
+
+ try {
+ // Slack
+ if (installation.integrationId === SLACK_INTEGRATION_ID) {
+ if (isAlreadyEncrypted(credentials.accessToken)) {
+ continue;
+ }
+
+ encryptedCredentials = {
+ ...credentials,
+ accessToken: encrypt(credentials.accessToken),
+ };
+ }
+
+ // Hubspot
+ else if (installation.integrationId === HUBSPOT_INTEGRATION_ID) {
+ if (isAlreadyEncrypted(credentials.access_token)) {
+ continue;
+ }
+
+ encryptedCredentials = {
+ ...credentials,
+ access_token: encrypt(credentials.access_token),
+ refresh_token: encrypt(credentials.refresh_token),
+ };
+ }
+
+ // Segment
+ else if (installation.integrationId === SEGMENT_INTEGRATION_ID) {
+ if (isAlreadyEncrypted(credentials.writeKey)) {
+ continue;
+ }
+
+ const schema = z.object({
+ writeKey: z.string(),
+ });
+
+ encryptedCredentials = schema.parse({
+ ...credentials,
+ writeKey: encrypt(credentials.writeKey),
+ });
+ }
+
+ // Shopify
+ else if (
+ installation.integrationId === SHOPIFY_INTEGRATION_ID &&
+ credentials?.accessToken
+ ) {
+ if (isAlreadyEncrypted(credentials.accessToken)) {
+ continue;
+ }
+
+ encryptedCredentials = {
+ ...credentials,
+ accessToken: encrypt(credentials.accessToken),
+ };
+ }
+
+ if (!encryptedCredentials) {
+ continue;
+ }
+
+ await prisma.installedIntegration.update({
+ where: {
+ id: installation.id,
+ },
+ data: {
+ credentials: encryptedCredentials,
+ },
+ });
+ } catch (error) {
+ console.error(`Failed to update installation ${installation.id}:`, error);
+ continue;
+ }
+ }
+}
+
+main();