keeweb/app/scripts/comp/app/chal-resp-calculator.js

66 lines
2.0 KiB
JavaScript
Raw Normal View History

import { Logger } from 'util/logger';
import { YubiKey } from 'comp/app/yubikey';
const logger = new Logger('chal-resp');
const ChalRespCalculator = {
cache: {},
2020-05-30 12:45:56 +02:00
getCacheKey(params) {
return `${params.vid}:${params.pid}:${params.serial}`;
},
build(params) {
if (!params) {
return null;
}
return challenge => {
return new Promise((resolve, reject) => {
const ts = logger.ts();
challenge = Buffer.from(challenge);
const hexChallenge = challenge.toString('hex');
2020-05-30 12:45:56 +02:00
const cacheKey = this.getCacheKey(params);
const respFromCache = this.cache[cacheKey]?.[hexChallenge];
2020-05-30 10:29:02 +02:00
if (respFromCache) {
logger.debug('Found ChalResp in cache');
2020-05-30 10:29:02 +02:00
return resolve(Buffer.from(respFromCache, 'hex'));
}
2020-05-30 10:29:02 +02:00
logger.debug('Calculating ChalResp using a YubiKey', params);
YubiKey.calculateChalResp(params, challenge, (err, response) => {
if (err) {
2020-05-30 10:29:02 +02:00
if (err.noKey) {
logger.debug('No YubiKey');
// TODO
return;
}
if (err.touchRequested) {
logger.debug('YubiKey touch requested');
// TODO
return;
}
return reject(err);
}
2020-05-30 10:29:02 +02:00
2020-05-30 12:45:56 +02:00
if (!this.cache[cacheKey]) {
this.cache[cacheKey] = {};
2020-05-30 10:29:02 +02:00
}
2020-05-30 12:45:56 +02:00
this.cache[cacheKey][hexChallenge] = response.toString('hex');
2020-05-30 10:29:02 +02:00
logger.info('Calculated ChalResp', logger.ts(ts));
resolve(response);
});
});
};
2020-05-30 12:45:56 +02:00
},
clearCache(params) {
delete this.cache[this.getCacheKey(params)];
}
};
export { ChalRespCalculator };