smartid-calls
Version:
Smart-ID client module for Node.JS with proxy layer
83 lines (62 loc) • 2.1 kB
text/typescript
import { ModuleConfigI } from '../types/Request';
import * as crypto from 'crypto';
import * as x509 from 'x509';
import axios from 'axios';
const CERT_BEGIN = '-----BEGIN CERTIFICATE-----\n';
const CERT_END = '\n-----END CERTIFICATE-----';
export class Session {
private config: ModuleConfigI;
private id: string;
constructor(config: ModuleConfigI, id: string) {
this.config = config;
this.id = id;
}
public async pollStatus(): Promise<any> {
const response = await axios({
method: 'GET',
proxy: this.config.proxy || false,
responseType: 'json',
validateStatus: (status) => status === 200,
url: this.config.host + '/session/'+ this.id + '?timeoutMs=10000'
});
if (typeof response !== 'object') {
throw new Error('Invalid response');
}
const body = response.data;
if (body.state && body.state === 'RUNNING') {
return await this.pollStatus();
}
if (!body.result) {
throw new Error('Invalid response (empty result)');
} else if (body.result.endResult !== 'OK') {
throw new Error(body.result.endResult);
} else {
const cert = CERT_BEGIN + body.cert.value + CERT_END;
return {
data: x509.getSubject(cert),
result: body.result,
all: body,
};
}
}
public async verifyRequest(prevRequest: any, authHash?: string) {
const cert = CERT_BEGIN + prevRequest.cert.value + CERT_END;
// Check that auth was properly signed
if (authHash) {
const verifier = crypto.createVerify(prevRequest.signature.algorithm);
verifier.update(Buffer.from(authHash, 'hex'));
if (!verifier.verify(cert, prevRequest.signature.value, 'base64')) {
return false;
}
}
// check if cert is active and not expired:
const parsedCert = x509.parseCert(cert);
const date = new Date();
if (parsedCert.notBefore > date) {
throw new Error('Certificate is not active yet');
} else if (parsedCert.notAfter < date) {
throw new Error('Certificate has expired');
}
return true;
}
}