Skip to content

Commit

Permalink
fix: assert state is short enough to be stored in cookie
Browse files Browse the repository at this point in the history
  • Loading branch information
Bekacru committed Oct 15, 2024
1 parent 58b7e3b commit 0f21842
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 7 deletions.
1 change: 0 additions & 1 deletion demo/nextjs/components/sign-in.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,6 @@ export default function SignIn() {
onClick={async () => {
await signIn.social({
provider: "discord",
callbackURL: "/dashboard",
});
}}
>
Expand Down
3 changes: 1 addition & 2 deletions packages/better-auth/src/api/routes/sign-in.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,7 @@ export const signInOAuth = createAuthEndpoint(
: `${currentURL?.origin}${c.body.callbackURL || ""}`;

const state = generateState(
callbackURL || currentURL?.origin || c.context.baseURL,
c.query?.currentURL,
callbackURL || currentURL?.origin || c.context.options.baseURL,
);
await c.setSignedCookie(
cookie.state.name,
Expand Down
3 changes: 1 addition & 2 deletions packages/better-auth/src/plugins/generic-oauth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,7 @@ export const genericOAuth = (options: GenericOAuthOptions) => {
? ctx.body.callbackURL
: `${currentURL?.origin}${ctx.body.callbackURL || ""}`;
const state = generateState(
callbackURL || currentURL?.origin || ctx.context.baseURL,
ctx.query?.currentURL,
callbackURL || currentURL?.origin || ctx.context.options.baseURL,
);
const cookie = ctx.context.authCookies;
await ctx.setSignedCookie(
Expand Down
9 changes: 7 additions & 2 deletions packages/better-auth/src/utils/state.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import { generateState as generateStateOAuth } from "oslo/oauth2";
import { z } from "zod";
import { BetterAuthError } from "../error/better-auth-error";

export function generateState(callbackURL?: string, currentURL?: string) {
export function generateState(callbackURL?: string) {
const code = generateStateOAuth();
const state = JSON.stringify({
code,
callbackURL,
currentURL,
});
if (state.length > 4000) {
throw new BetterAuthError(
"State is too long to be safely stored in a cookie. Make sure the callbackURL is not too long.",
);
}
return state;
}

Expand Down

0 comments on commit 0f21842

Please sign in to comment.