Skip to content

Commit 74553ef

Browse files
bisandgithub-actions[bot]atinux
authored
fix: add explicit security options to OAuth cookies to prevent state mismatch errors (#463)
Co-authored-by: GitHub Copilot <github-actions[bot]@users.noreply.github.com> Co-authored-by: Sébastien Chopin <atinux@gmail.com>
1 parent c045489 commit 74553ef

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

src/runtime/server/lib/utils.ts

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,12 @@ import { subtle, getRandomValues } from 'uncrypto'
77
import type { OAuthProvider, OnError } from '#auth-utils'
88
import { createError } from '#imports'
99

10+
// Determine if we are in development mode
11+
const isDevelopment = process.env.NODE_ENV === 'development'
12+
13+
// OAuth cookie expiration time (10 minutes in seconds)
14+
const OAUTH_COOKIE_MAX_AGE = 60 * 10
15+
1016
export function getOAuthRedirectURL(event: H3Event): string {
1117
const requestURL = getRequestURL(event)
1218

@@ -187,7 +193,13 @@ export async function handlePkceVerifier(event: H3Event) {
187193
// Create new verifier
188194
if (!query.code) {
189195
const verifier = encodeBase64Url(getRandomBytes())
190-
setCookie(event, 'nuxt-auth-pkce', verifier)
196+
setCookie(event, 'nuxt-auth-pkce', verifier, {
197+
httpOnly: true,
198+
secure: !isDevelopment,
199+
sameSite: 'lax',
200+
maxAge: OAUTH_COOKIE_MAX_AGE,
201+
path: '/',
202+
})
191203

192204
// Get pkce
193205
const encodedPkce = new TextEncoder().encode(verifier)
@@ -218,6 +230,12 @@ export async function handleState(event: H3Event) {
218230

219231
// If the state is not in the query, generate a new state and set it in the cookie
220232
const state = encodeBase64Url(getRandomBytes(8))
221-
setCookie(event, 'nuxt-auth-state', state)
233+
setCookie(event, 'nuxt-auth-state', state, {
234+
httpOnly: true,
235+
secure: !isDevelopment,
236+
sameSite: 'lax',
237+
maxAge: OAUTH_COOKIE_MAX_AGE,
238+
path: '/',
239+
})
222240
return state
223241
}

0 commit comments

Comments
 (0)