Skip to content

[pull] main from baptisteArno:main #289

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions apps/builder/next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ const nextConfig = {
config.resolve.alias["minio"] = false;
config.resolve.alias["qrcode"] = false;
config.resolve.alias["isolated-vm"] = false;
config.resolve.alias["@googleapis/gmail"] = false;
config.resolve.alias["nodemailer"] = false;
config.resolve.alias["google-auth-library"] = false;
return config;
},
headers: async () => {
Expand Down
2 changes: 1 addition & 1 deletion apps/builder/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
"dequal": "2.0.3",
"emojilib": "3.0.10",
"framer-motion": "11.1.7",
"google-auth-library": "9.15.1",
"google-auth-library": "10.1.0",
"google-spreadsheet": "4.1.4",
"immer": "10.0.2",
"ioredis": "5.4.1",
Expand Down
50 changes: 50 additions & 0 deletions apps/builder/src/app/api/[blockType]/oauth/authorize/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { env } from "@typebot.io/env";
import { forgedBlocks } from "@typebot.io/forge-repository/definitions";
import type { AuthDefinition, OAuthDefinition } from "@typebot.io/forge/types";
import { z } from "@typebot.io/zod";
import { type NextRequest, NextResponse } from "next/server";

const searchParamsSchema = z.object({
clientId: z.string().optional(),
});

export const GET = async (
req: NextRequest,
{ params }: { params: Promise<{ blockType: string }> },
) => {
const { blockType } = await params;
const authConfig = forgedBlocks[blockType as keyof typeof forgedBlocks].auth;
if (!isOAuthDefinition(authConfig))
return NextResponse.json({ error: "Invalid block type" }, { status: 400 });
const { success, data, error } = searchParamsSchema.safeParse(
Object.fromEntries(req.nextUrl.searchParams),
);
if (!success)
return NextResponse.json({ error: error.message }, { status: 400 });
const clientId =
data.clientId ||
(authConfig.defaultClientEnvKeys
? process.env[authConfig.defaultClientEnvKeys.id]
: undefined);
if (!clientId)
return NextResponse.json(
{ error: "Client ID is required" },
{ status: 400 },
);
const url = new URL(authConfig.authUrl);
const urlParams = {
response_type: "code",
client_id: clientId,
redirect_uri: `${env.NEXTAUTH_URL}/oauth/redirect`,
scope: authConfig.scopes.join(" "),
...authConfig.extraAuthParams,
};
Object.entries(urlParams).forEach(([k, v]) => url.searchParams.append(k, v));
return NextResponse.redirect(url);
};

const isOAuthDefinition = (
authConfig: AuthDefinition<any> | undefined,
): authConfig is OAuthDefinition => {
return !!authConfig && authConfig.type === "oauth";
};
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,16 @@ export const getSpreadsheetName = authenticatedProcedure
workspaceId,
);

if (!client)
if (!client?.credentials.access_token)
throw new TRPCError({
code: "NOT_FOUND",
message: "Google client could not be initialized",
});

try {
const googleSheet = new GoogleSpreadsheet(spreadsheetId, client);
const googleSheet = new GoogleSpreadsheet(spreadsheetId, {
token: client.credentials.access_token,
});

await googleSheet.loadInfo();

Expand Down

This file was deleted.

192 changes: 192 additions & 0 deletions apps/builder/src/features/credentials/api/createOAuthCredentials.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
import { isWriteWorkspaceForbidden } from "@/features/workspace/helpers/isWriteWorkspaceForbidden";
import { authenticatedProcedure } from "@/helpers/server/trpc";
import { TRPCError } from "@trpc/server";
import { encrypt } from "@typebot.io/credentials/encrypt";
import { env } from "@typebot.io/env";
import { forgedBlocks } from "@typebot.io/forge-repository/definitions";
import type { OAuthDefinition } from "@typebot.io/forge/types";
import { parseUnknownError } from "@typebot.io/lib/parseUnknownError";
import prisma from "@typebot.io/prisma";
import { z } from "@typebot.io/zod";
import ky from "ky";

const commonInput = z.object({
name: z.string(),
blockType: z.string(),
code: z.string(),
customClient: z
.object({
id: z.string(),
secret: z.string(),
})
.optional(),
});

export const createOAuthCredentials = authenticatedProcedure
.input(
z.discriminatedUnion("scope", [
z
.object({
scope: z.literal("workspace"),
workspaceId: z.string(),
})
.merge(commonInput),
z
.object({
scope: z.literal("user"),
})
.merge(commonInput),
]),
)
.output(
z.object({
credentialsId: z.string(),
}),
)
.mutation(async ({ input, ctx: { user } }) => {
const blockDef = forgedBlocks[input.blockType as keyof typeof forgedBlocks];
if (!blockDef || blockDef.auth?.type !== "oauth")
throw new TRPCError({
code: "BAD_REQUEST",
message: "Block is not an OAuth block",
});

const client = getClient(input.customClient, blockDef.auth);

if (!client)
throw new TRPCError({
code: "BAD_REQUEST",
message: "No client ID or secret provided or default client not set",
});

const tokens = await exchangeCodeForTokens({
tokenUrl: blockDef.auth.tokenUrl,
client,
code: input.code,
});

const { encryptedData, iv } = await encrypt({
...tokens,
client: input.customClient,
});

if (input.scope === "user") {
const createdCredentials = await prisma.userCredentials.create({
data: {
name: input.name,
type: input.blockType,
userId: user.id,
data: encryptedData,
iv,
},
select: {
id: true,
},
});

return { credentialsId: createdCredentials.id };
}
const workspace = await prisma.workspace.findFirst({
where: {
id: input.workspaceId,
},
select: { id: true, members: { select: { userId: true, role: true } } },
});
if (!workspace || isWriteWorkspaceForbidden(workspace, user))
throw new TRPCError({
code: "NOT_FOUND",
message: "Workspace not found",
});

const createdCredentials = await prisma.credentials.create({
data: {
name: input.name,
type: input.blockType,
workspaceId: input.workspaceId,
data: encryptedData,
iv,
},
select: {
id: true,
},
});

return { credentialsId: createdCredentials.id };
});

const exchangeCodeForTokens = async ({
tokenUrl,
client,
code,
}: {
tokenUrl: string;
client: { id: string; secret: string };
code: string;
}) => {
try {
const tokens = await ky
.post(tokenUrl, {
json: {
grant_type: "authorization_code",
code: code,
client_id: client.id,
client_secret: client.secret,
redirect_uri: `${env.NEXTAUTH_URL}/oauth/redirect`,
},
})
.json();

if (
!tokens ||
typeof tokens !== "object" ||
!("access_token" in tokens) ||
!("refresh_token" in tokens) ||
!("expires_in" in tokens) ||
typeof tokens.access_token !== "string" ||
typeof tokens.refresh_token !== "string" ||
typeof tokens.expires_in !== "number"
)
throw new TRPCError({
code: "BAD_REQUEST",
message: "Invalid tokens returned from the auth provider",
});

if (!tokens.refresh_token) {
return {
error: {
context: "token exchange",
description: "No refresh_token returned",
},
};
}

return {
accessToken: tokens.access_token,
refreshToken: tokens.refresh_token,
expiryDate: Date.now() + (tokens.expires_in ?? 0) * 1000,
};
} catch (err) {
const parsedError = await parseUnknownError({
err,
context: "token exchange",
});
console.error(parsedError);
throw new TRPCError({
code: "BAD_REQUEST",
message: parsedError.description,
});
}
};

const getClient = (
customClient: { id: string; secret: string } | undefined,
authDef: OAuthDefinition,
) => {
if (customClient) return customClient;
if (authDef.defaultClientEnvKeys) {
const id = process.env[authDef.defaultClientEnvKeys.id];
const secret = process.env[authDef.defaultClientEnvKeys.secret];
if (id && secret) return { id, secret };
}
return undefined;
};
4 changes: 4 additions & 0 deletions apps/builder/src/features/credentials/api/router.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { router } from "@/helpers/server/trpc";
import { createCredentials } from "./createCredentials";
import { createOAuthCredentials } from "./createOAuthCredentials";
import { deleteCredentials } from "./deleteCredentials";
import { getCredentials } from "./getCredentials";
import { listCredentials } from "./listCredentials";
import { updateCredentials } from "./updateCredentials";
import { updateOAuthCredentials } from "./updateOAuthCredentials";

export const credentialsRouter = router({
createCredentials,
createOAuthCredentials,
updateOAuthCredentials,
listCredentials,
getCredentials,
deleteCredentials,
Expand Down
Loading
Loading