import * as jwt from "jsonwebtoken" ; import { pruneCert } from "./utils" ; import uuid = require ( "uuid" ) ; export class implements TokenRotation export class MqttOpcUaAuth { param { string } _clientid param { string } _rootca param { string } _devicecrt param { number } _expiration param { string } _devicekey param { string } _intermediate param { string } _passphrase param { string } _tenant memberOf constructor ( private _clientid , private _rootca , private _devicecrt , private _expiration , private _devicekey , private _intermediate ? , private _passphrase ? , private _tenant ? ) { } private _token ? : string ; public GetMqttToken ( ) { if ( ! this . ValidateToken ( ) ) { this . _token = undefined ; } if ( ! this . _token ) { this . _token = this . CreateToken ( ) ; } return this . _token ; } private ValidateToken ( ) { let result = false ; if ( this . _token ) { const token = jwt . decode ( this . _token ) as any ; const now = Math . round ( new Date ( ) . getTime ( ) / 1000 ) ; result = now < token . exp ; } return result ; } private CreateToken ( ) { const tokenHeader = { alg : "RS256" , x5c : [ ] , typ : "JWT" , } ; const tokenBody = { aud : [ "MQTTBroker" ] , schemas : [ "urn:siemens:mindsphere:v1" ] , } ; tokenBody . iss = this . _clientid ; tokenBody . sub = this . _clientid ; tokenHeader . x5c . push ( pruneCert ( this . _devicecrt ) ) ; this . _intermediate && tokenHeader . x5c . push ( pruneCert ( this . _intermediate ) ) ; tokenHeader . x5c . push ( pruneCert ( this . _rootca ) ) ; const issuedTime = Math . round ( new Date ( ) . getTime ( ) / 1000 ) ; const expirationTime = issuedTime + this . _expiration ; tokenBody . jti = uuid . v4 ( ) . toString ( ) ; tokenBody . iat = issuedTime ; tokenBody . nbf = issuedTime ; tokenBody . exp = expirationTime ; tokenBody . ten = `${ this . _tenant }` ; const signOptions = { key : this . _devicekey , } ; if ( this . _passphrase ) { signOptions . passphrase = `${ this . _passphrase }` ; } const signedJwt = jwt . sign ( tokenBody , signOptions , { header : tokenHeader , algorithm : "RS256" } ) ; return signedJwt ; } returns { Promise < boolean > } memberOf public async RenewToken ( ) { if ( ! this . ValidateToken ( ) ) { this . _token = this . CreateToken ( ) ; } return true ; } }