import base64url from 'base64url' ; import ErrorHelpers from '../error_handling/ErrorHelpers' ; import ValidationError from '../error_handling/ValidationError' ; const errorCode = ( error ) => ErrorHelpers . errorCode ( 'VCSDKJWST' , error ) ; /**
 * Type that describes an object that maps a key to a value.
 */ export type TokenPayload = { [ claim ] : any ; } ; /**
 * class for parsing unecrypted Json Web Tokens
 */ export default class JsonWebSignatureToken { /**
     * The expected number of parts for a JWS compact token
     */ private static readonly EXPECTED_PARTS : number = 3 ; /**
     * Encoding of the header as mandated per JWS rfc: https://tools.ietf.org/html/rfc7515#section-2
     */ private static readonly UTF8_ENCODING = 'utf8' ; /**
     * flag indicating whether or not the token is an unsecured jws
     */ public readonly unsecured : boolean ; /**
     * Decoded header of the token
     */ public readonly header : TokenPayload ; /**
     * decoded payload of the token
     */ public readonly payload : TokenPayload ; /**
     * encoded signature of the token
     */ public readonly signature : string ; /**
     * the length of the pre-image of the token
     * per RFC7515: https://tools.ietf.org/html/rfc7515#section-3.3
     */ private readonly preimageLength : number ; param token constructor ( public readonly token ) { const parts = token . split ( '.' ) ; if ( parts . length < JsonWebSignatureToken . EXPECTED_PARTS ) { throw new ValidationError ( 'Invalid json web token' , errorCode ( 1 ) ) ; } this . header = JsonWebSignatureToken . parsePayload ( parts [ 0 ] , 'header' , 2 ) ; this . payload = JsonWebSignatureToken . parsePayload ( parts [ 1 ] , 'payload' , 3 ) ; this . signature = parts [ 2 ] ; this . unsecured = ! parts [ 2 ] ; this . preimageLength = 1 + parts [ 0 ] . length + parts [ 1 ] . length ; } param header param payload returns public static encode ( header , payload ) { const encodedHeader = base64url . encode ( JSON . stringify ( header ) , JsonWebSignatureToken . UTF8_ENCODING ) ; const encodedPayload = base64url . encode ( JSON . stringify ( payload ) , JsonWebSignatureToken . UTF8_ENCODING ) ; return new JsonWebSignatureToken ( `${ encodedHeader }.${ encodedPayload }.` ) ; } param encodedPart param name param scenario returns private static parsePayload ( encodedPart , name , scenario ) { try { return JSON . parse ( base64url . decode ( encodedPart ) ) ; } catch ( error ) { throw new ValidationError ( `Invalid json web token the ${ name } is malformed` , errorCode ( scenario ) ) ; } } }