@@ -6,6 +6,17 @@ import { UnauthorizedError } from '@crowd/common'
66import type { Auth0Configuration } from '@/conf/configTypes'
77import type { Auth0TokenPayload } from '@/types/api'
88
9+ function resolveIssuer ( req : Request ) : string | undefined {
10+ const token = req . headers . authorization ?. split ( ' ' ) [ 1 ]
11+ if ( ! token ) return undefined
12+ try {
13+ const { iss } = JSON . parse ( Buffer . from ( token . split ( '.' ) [ 1 ] , 'base64url' ) . toString ( ) )
14+ return typeof iss === 'string' ? iss : undefined
15+ } catch {
16+ return undefined
17+ }
18+ }
19+
920function resolveActor ( req : Request , _res : Response , next : NextFunction ) : void {
1021 const payload = ( req . auth ?. payload ?? { } ) as Auth0TokenPayload
1122
@@ -26,11 +37,38 @@ function resolveActor(req: Request, _res: Response, next: NextFunction): void {
2637}
2738
2839export function oauth2Middleware ( config : Auth0Configuration ) : RequestHandler [ ] {
29- return [
30- auth ( {
31- issuerBaseURL : config . issuerBaseURL ,
32- audience : config . audience ,
33- } ) ,
34- resolveActor ,
35- ]
40+ const issuers = config . issuerBaseURLs
41+ . split ( ',' )
42+ . map ( ( s ) => s . trim ( ) )
43+ . filter ( Boolean )
44+
45+ if ( issuers . length === 0 ) {
46+ throw new Error ( 'No auth0 issuers configured' )
47+ }
48+
49+ const handlersByIssuer = new Map (
50+ issuers . map ( ( issuerBaseURL ) => [
51+ issuerBaseURL . replace ( / \/ $ / , '' ) ,
52+ auth ( { issuerBaseURL, audience : config . audience } ) ,
53+ ] ) ,
54+ )
55+
56+ const verifyJwt : RequestHandler = ( req , res , next ) => {
57+ const iss = resolveIssuer ( req )
58+ if ( ! iss ) {
59+ next ( new UnauthorizedError ( 'Missing or malformed bearer token' ) )
60+ return
61+ }
62+
63+ const handler = handlersByIssuer . get ( iss . replace ( / \/ $ / , '' ) )
64+
65+ if ( ! handler ) {
66+ next ( new UnauthorizedError ( 'Unknown token issuer' ) )
67+ return
68+ }
69+
70+ handler ( req , res , next )
71+ }
72+
73+ return [ verifyJwt , resolveActor ]
3674}
0 commit comments