11import { IncomingMessage } from 'node:http' ;
22import { CAT } from '..' ;
3+ import {
4+ InvalidAudienceError ,
5+ InvalidIssuerError ,
6+ KeyNotFoundError ,
7+ TokenExpiredError
8+ } from '../errors' ;
39
410interface HttpValidatorKey {
511 kid : string ;
612 key : Buffer ;
713}
814
915export interface HttpValidatorOptions {
16+ tokenMandatory ?: boolean ;
1017 keys : HttpValidatorKey [ ] ;
1118 issuer : string ;
1219 audience ?: string [ ] ;
@@ -17,6 +24,12 @@ export interface HttpResponse {
1724 message ?: string ;
1825}
1926
27+ export class NoTokenFoundError extends Error {
28+ constructor ( ) {
29+ super ( 'No CTA token could be found' ) ;
30+ }
31+ }
32+
2033/**
2134 * Handle request and validate CTA Common Access Token
2235 *
@@ -49,6 +62,7 @@ export class HttpValidator {
4962 this . keys [ k . kid ] = k . key ;
5063 } ) ;
5164 this . opts = opts ;
65+ this . opts . tokenMandatory = opts . tokenMandatory ?? true ;
5266 }
5367
5468 public async validateHttpRequest (
@@ -60,17 +74,32 @@ export class HttpValidator {
6074
6175 // Check for token in headers first
6276 if ( request . headers [ 'cta-common-access-token' ] ) {
63- const token = request . headers [ 'cta-common-access-token' ] as string ;
77+ const token = Array . isArray ( request . headers [ 'cta-common-access-token' ] )
78+ ? request . headers [ 'cta-common-access-token' ] [ 0 ]
79+ : request . headers [ 'cta-common-access-token' ] ;
6480 try {
6581 await validator . validate ( token , 'mac' , {
6682 issuer : this . opts . issuer ,
6783 audience : this . opts . audience
6884 } ) ;
6985 return { status : 200 } ;
7086 } catch ( err ) {
71- return { status : 401 , message : ( err as Error ) . message } ;
87+ if (
88+ err instanceof InvalidIssuerError ||
89+ err instanceof InvalidAudienceError ||
90+ err instanceof KeyNotFoundError ||
91+ err instanceof TokenExpiredError
92+ ) {
93+ return { status : 401 , message : ( err as Error ) . message } ;
94+ } else {
95+ console . log ( `Internal error` , err ) ;
96+ return { status : 500 , message : ( err as Error ) . message } ;
97+ }
7298 }
7399 }
74- throw new Error ( 'No CTA token could be found' ) ;
100+ if ( this . opts . tokenMandatory ) {
101+ throw new NoTokenFoundError ( ) ;
102+ }
103+ return { status : 200 } ;
75104 }
76105}
0 commit comments