import { createHash } from 'crypto' ; import * as moment from 'moment' ; import { Injectable } from '@nestjs/common' ; import { ConfigService } from '@fc/config' ; import { EidasLightProtocolConfig } from '../dto' ; import { EidasInvalidTokenChecksumException , EidasOversizedTokenException , } from '../exceptions' ; import { IParsedToken } from '../interfaces' ; @ Injectable ( ) export class LightProtocolCommonsService { constructor ( private readonly config ) { } param id param issuer param secret param date returns generateToken ( id , issuer , secret , date ? ) { const finalDate = moment ( date ) . format ( 'YYYY-MM-DD HH:mm:ss SSS' ) ; const digest = this . generateTokenDigest ( id , issuer , secret , finalDate ) ; const lRToken = `${ issuer }|${ id }|${ finalDate }|${ digest }` ; return Buffer . from ( lRToken , 'utf8' ) . toString ( 'base64' ) ; } param token param secret returns parseToken ( token , secret ) { const { maxTokenSize } = this . config . get < EidasLightProtocolConfig > ( 'EidasLightProtocol' ) ; if ( token . length > maxTokenSize ) { throw new EidasOversizedTokenException ( ) ; } const decodedToken = Buffer . from ( token , 'base64' ) . toString ( 'utf8' ) ; const [ issuer , id , date , decodedDigest ] = decodedToken . split ( '|' ) ; const computedDigest = this . generateTokenDigest ( id , issuer , secret , date ) ; if ( decodedDigest !== computedDigest ) { throw new EidasInvalidTokenChecksumException ( ) ; } return { issuer , id , date : moment ( date , 'YYYY-MM-DD HH:mm:ss SSS' ) . toDate ( ) , } ; } param value returns getLastElementInUrlOrUrn < T > ( value ) { return value . split ( /[:/]/ ) . pop ( ) as unknown as T ; } param id param issuer param secret param date returns private generateTokenDigest ( id , issuer , secret , date ) { const hash = createHash ( 'sha256' ) ; hash . update ( `${ id }|${ issuer }|${ date }|${ secret }` ) ; return hash . digest ( 'base64' ) ; } }