homebridge-flume
Version:
Homebridge plugin to integrate Flume devices into HomeKit.
68 lines • 2.37 kB
JavaScript
import crypto from 'crypto';
import { DAY, SECOND } from '../tools/time.js';
import { jwtDecode } from 'jwt-decode';
import { storageGet, storageSet, STORAGE_KEY_AUTH } from '../tools/storage.js';
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();
}
async save(persistPath, encryptionKey) {
try {
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');
await storageSet(persistPath, STORAGE_KEY_AUTH, final);
}
catch (err) {
// Nothing
}
}
static async load(persistPath, encryptionKey) {
try {
const final = await storageGet(persistPath, STORAGE_KEY_AUTH);
if (!final) {
return null;
}
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