Skip to content

Commit c48c76e

Browse files
authored
Fix statelessSessions to only accept Authorization: Bearer prefixed tokens (#9786)
1 parent d0316ee commit c48c76e

1 file changed

Lines changed: 13 additions & 4 deletions

File tree

packages/core/src/session.ts

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { randomBytes } from 'node:crypto'
22
import * as cookie from 'cookie'
33
import Iron from '@hapi/iron'
4-
import type { SessionStrategy, SessionStoreFunction } from '../types'
4+
import type { KeystoneContext, SessionStrategy, SessionStoreFunction } from '../types'
55

66
// TODO: should we also accept httpOnly?
77
type StatelessSessionsOptions = {
@@ -59,6 +59,17 @@ type StatelessSessionsOptions = {
5959
sameSite?: true | false | 'lax' | 'strict' | 'none'
6060
}
6161

62+
function getToken(req: NonNullable<KeystoneContext['req']>, cookieName: string) {
63+
const authorization = req.headers.authorization ?? ''
64+
65+
if (authorization.startsWith('Bearer')) {
66+
return authorization.slice('Bearer '.length)
67+
}
68+
69+
const cookies = cookie.parse(req.headers.cookie || '')
70+
return cookies[cookieName]
71+
}
72+
6273
export function statelessSessions<Session>({
6374
secret = randomBytes(32).toString('base64url'),
6475
maxAge = 60 * 60 * 8, // 8 hours,
@@ -78,9 +89,7 @@ export function statelessSessions<Session>({
7889
async get({ context }) {
7990
if (!context?.req) return
8091

81-
const cookies = cookie.parse(context.req.headers.cookie || '')
82-
const bearer = context.req.headers.authorization?.replace('Bearer ', '')
83-
const token = bearer || cookies[cookieName]
92+
const token = getToken(context.req, cookieName)
8493
if (!token) return
8594
try {
8695
return await Iron.unseal(token, secret, ironOptions)

0 commit comments

Comments
 (0)