11import { randomBytes } from 'node:crypto'
22import * as cookie from 'cookie'
33import 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?
77type 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+
6273export 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