Files
calendar/packages/trpc/server/routers/viewer/oAuth/generateAuthCode.handler.ts
T
Carina WollendorferGitHubcubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>CarinaWollicubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
4e0798577a feat: OAuth PKCE (#25313)
* add public client

* implement PKCE

* pass codeChallenge and codeChallengeMethod to handler

* fixes for secure oauth flow

* fix type error

* clean up refresh token endpoint

* only support S256

* fix type error

* remove comment

* add tests

* fix type errors in route.test.ts

* add missing support for refresh token

* add e2e test for public client refresh tokens

* allow pkce for confidential clients

* fix type error

* fix e2e

* fix option pkce for confidential clients

* e2e test improvements

* fix test

* remove only

* add delay

* fix e2e tests

* remove only

* don't skip pkce if codeChallenge is set

* add service functions for token endpoint

* use service function in refreshToken endpoint

* use repository

* remove return types

* e2e test fixes

* fix e2e test

* remove .only in e2e test

* remove pause

* fix error responses in token endpoints

* adjust tests to new error responses

* fix error responses

* e2e improvements

* redirect on error

* adjust tests

* Update apps/web/modules/auth/oauth2/authorize-view.tsx

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-11-26 17:02:42 +01:00

106 lines
2.8 KiB
TypeScript

import { randomBytes } from "crypto";
import dayjs from "@calcom/dayjs";
import { prisma } from "@calcom/prisma";
import type { AccessScope } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { TRPCError } from "@trpc/server";
import type { TGenerateAuthCodeInputSchema } from "./generateAuthCode.schema";
type AddClientOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TGenerateAuthCodeInputSchema;
};
export const generateAuthCodeHandler = async ({ ctx, input }: AddClientOptions) => {
const { clientId, scopes, teamSlug, codeChallenge, codeChallengeMethod } = input;
const client = await prisma.oAuthClient.findUnique({
where: {
clientId,
},
select: {
clientId: true,
redirectUri: true,
name: true,
clientType: true,
},
});
if (!client) {
throw new TRPCError({ code: "UNAUTHORIZED", message: "Client ID not valid" });
}
if (client.clientType === "PUBLIC") {
if (!codeChallenge) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "code_challenge required for public clients",
});
}
if (!codeChallengeMethod || codeChallengeMethod !== "S256") {
throw new TRPCError({
code: "BAD_REQUEST",
message: "code_challenge_method must be S256 for public clients",
});
}
} else if (client.clientType === "CONFIDENTIAL") {
// Optional PKCE validation for CONFIDENTIAL clients
if (codeChallenge && (!codeChallengeMethod || codeChallengeMethod !== "S256")) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "code_challenge_method must be S256 when PKCE is used",
});
}
}
const authorizationCode = generateAuthorizationCode();
const team = teamSlug
? await prisma.team.findFirst({
where: {
slug: teamSlug,
members: {
some: {
userId: ctx.user.id,
role: {
in: ["OWNER", "ADMIN"],
},
},
},
},
})
: undefined;
if (teamSlug && !team) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
await prisma.accessCode.create({
data: {
code: authorizationCode,
clientId,
userId: !teamSlug ? ctx.user.id : undefined,
teamId: team ? team.id : undefined,
expiresAt: dayjs().add(10, "minutes").toDate(),
scopes: scopes as [AccessScope],
codeChallenge,
codeChallengeMethod,
},
});
return { client, authorizationCode };
};
function generateAuthorizationCode() {
const randomBytesValue = randomBytes(40);
const authorizationCode = randomBytesValue
.toString("base64")
.replace(/=/g, "")
.replace(/\+/g, "-")
.replace(/\//g, "_");
return authorizationCode;
}