65 lines
1.8 KiB
JavaScript
65 lines
1.8 KiB
JavaScript
|
|
import * as fs from 'fs';
|
||
|
|
import * as path from 'path';
|
||
|
|
import * as crypto from 'crypto';
|
||
|
|
/**
|
||
|
|
* Generate SHA256 hash for cache key
|
||
|
|
*/
|
||
|
|
export function sha256(input) {
|
||
|
|
return crypto.createHash('sha256').update(input).digest('hex');
|
||
|
|
}
|
||
|
|
/**
|
||
|
|
* Get cache file path for current AUTH_BASE and CLIENT_KEY
|
||
|
|
*/
|
||
|
|
export function getCacheFile(authBase, clientKey, cacheDir) {
|
||
|
|
const key = sha256(`${authBase}|${clientKey}`);
|
||
|
|
if (!fs.existsSync(cacheDir)) {
|
||
|
|
fs.mkdirSync(cacheDir, { recursive: true });
|
||
|
|
}
|
||
|
|
return path.join(cacheDir, `session_${key}.json`);
|
||
|
|
}
|
||
|
|
/**
|
||
|
|
* Read cached token if valid
|
||
|
|
*/
|
||
|
|
export function readCachedToken(cacheFile, minTtlSec) {
|
||
|
|
if (!fs.existsSync(cacheFile)) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
try {
|
||
|
|
const data = JSON.parse(fs.readFileSync(cacheFile, 'utf-8'));
|
||
|
|
const now = Math.floor(Date.now() / 1000);
|
||
|
|
if (!data.accessToken || data.expiresAtEpoch <= 0) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
// Check if token is still valid (with min TTL buffer)
|
||
|
|
if (now + minTtlSec >= data.expiresAtEpoch) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
return data.accessToken;
|
||
|
|
}
|
||
|
|
catch (error) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
/**
|
||
|
|
* Write token to cache
|
||
|
|
*/
|
||
|
|
export function writeCache(cacheFile, sessionJson) {
|
||
|
|
const nowEpoch = Math.floor(Date.now() / 1000);
|
||
|
|
const expiresIn = sessionJson.expiresIn > 0 ? sessionJson.expiresIn : 900;
|
||
|
|
const expiresAtEpoch = nowEpoch + expiresIn;
|
||
|
|
const cacheData = {
|
||
|
|
accessToken: sessionJson.accessToken,
|
||
|
|
expiresAtEpoch,
|
||
|
|
createdAtEpoch: nowEpoch,
|
||
|
|
};
|
||
|
|
fs.writeFileSync(cacheFile, JSON.stringify(cacheData, null, 2), 'utf-8');
|
||
|
|
}
|
||
|
|
/**
|
||
|
|
* Delete cache file if exists
|
||
|
|
*/
|
||
|
|
export function deleteCache(cacheFile) {
|
||
|
|
if (fs.existsSync(cacheFile)) {
|
||
|
|
fs.unlinkSync(cacheFile);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
//# sourceMappingURL=cache.js.map
|