homebridge-flume
Version:
Homebridge plugin to integrate Flume devices into HomeKit.
64 lines • 2.22 kB
JavaScript
import crypto from 'crypto';
import { safeSetItem, safeGetItem } from '../tools/storage.js';
import { DAY, SECOND } from '../tools/time.js';
import { jwtDecode } from 'jwt-decode';
const STORAGE_AUTH_KEY = 'auth';
export class Auth {
data;
created;
_userId;
constructor(data, created = Date.now()) {
this.data = data;
this.created = created;
}
get token() {
return this.data.access_token;
}
get userId() {
if (!this._userId) {
this._userId = jwtDecode(this.token).user_id;
}
return this._userId;
}
get refresh() {
return this.data.refresh_token;
}
get expiry() {
return this.created + (this.data.expires_in * SECOND) - DAY;
}
static digest(encryptionKey) {
return crypto.createHash('sha256').update(encryptionKey).digest();
}
save(filePath, encryptionKey) {
const serailzed = JSON.stringify({
data: this.data,
created: this.created,
});
const digest = Auth.digest(encryptionKey);
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', digest, iv);
const encrypted = Buffer.concat([cipher.update(serailzed, 'utf8'), cipher.final()]);
const final = iv.toString('hex') + ':' + encrypted.toString('hex');
safeSetItem(filePath, STORAGE_AUTH_KEY, final);
}
static load(filePath, encryptionKey) {
const final = safeGetItem(filePath, STORAGE_AUTH_KEY);
if (!final) {
return null;
}
try {
const digest = Auth.digest(encryptionKey);
const [ivHex, encryptedHex] = final.split(':');
const iv = Buffer.from(ivHex, 'hex');
const encrypted = Buffer.from(encryptedHex, 'hex');
const decipher = crypto.createDecipheriv('aes-256-cbc', digest, iv);
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf8');
const obj = JSON.parse(decrypted);
return new Auth(obj.data, obj.created);
}
catch {
return null;
}
}
}
//# sourceMappingURL=auth.js.map