109 lines
3.8 KiB
TypeScript
109 lines
3.8 KiB
TypeScript
import * as crypto from "crypto";
|
|
import * as path from "path";
|
|
import { promises as fs , existsSync, mkdirSync } from "fs";
|
|
|
|
const dataDir = path.join(process.cwd(), 'data');
|
|
if (!existsSync(dataDir)) {
|
|
mkdirSync(dataDir);
|
|
}
|
|
|
|
export class Encryptor {
|
|
private static magic = "";
|
|
private static validatorFile = 'key-validator';
|
|
private constructor(private key: Buffer, private filePath: string) {}
|
|
|
|
static setMagic(magic: string) {
|
|
Encryptor.magic = magic;
|
|
}
|
|
|
|
static async exist(identifier: string, key: string) {
|
|
identifier = this.makeFileSafeString(identifier);
|
|
const storeDirectory = path.join(dataDir, identifier);
|
|
const validatorFileBin = path.join(storeDirectory, `${this.validatorFile}.bin`);
|
|
const keyHash = crypto.createHash('sha256').update(key).digest()
|
|
try {
|
|
await fs.access(validatorFileBin)
|
|
} catch (error) {
|
|
return false;
|
|
};
|
|
|
|
const en = new Encryptor(keyHash, validatorFileBin);
|
|
try {
|
|
const validator = await en.decrypt();
|
|
|
|
if (!validator || validator.toString('utf8') !== Encryptor.magic) {
|
|
return false;
|
|
}
|
|
} catch (error) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static async createEncryptor(identifier: string, key: string, file: string) {
|
|
if (file === this.validatorFile)
|
|
throw new Error(`File cannot be ${this.validatorFile}`);
|
|
|
|
identifier = this.makeFileSafeString(identifier);
|
|
const storeDirectory = path.join(dataDir, identifier);
|
|
const validatorFileBin = path.join(storeDirectory, `${this.validatorFile}.bin`);
|
|
const writableDir = path.join(storeDirectory, `${file}.bin`);
|
|
const keyHash = crypto.createHash('sha256').update(key).digest()
|
|
|
|
const en = new Encryptor(keyHash, validatorFileBin);
|
|
try {
|
|
await fs.access(validatorFileBin)
|
|
} catch (error) {
|
|
if (!existsSync(storeDirectory)) {
|
|
mkdirSync(storeDirectory);
|
|
}
|
|
await en.encrypt(Buffer.from(Encryptor.magic, 'utf8'));
|
|
return new Encryptor(keyHash, file);
|
|
};
|
|
const validator = await en.decrypt();
|
|
|
|
if (!validator || validator.toString('utf8') !== Encryptor.magic) {
|
|
throw new Error("Invalid key");
|
|
}
|
|
return new Encryptor(keyHash, writableDir);
|
|
}
|
|
|
|
static makeFileSafeString(input: string) {
|
|
return input
|
|
.replace(/\s+/g, '_')
|
|
.replace(/[^a-zA-Z0-9_.-]/g, '')
|
|
.substring(0, 255);
|
|
}
|
|
|
|
private encryptBuffer(data: Buffer): Buffer {
|
|
const iv = crypto.randomBytes(16);
|
|
const cipher = crypto.createCipheriv('aes-256-cbc', this.key, iv);
|
|
const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
|
|
return Buffer.concat([iv, encrypted]);
|
|
}
|
|
|
|
private decryptBuffer(buffer: Buffer): Buffer {
|
|
const iv = buffer.subarray(0, 16);
|
|
const encryptedData = buffer.subarray(16);
|
|
const decipher = crypto.createDecipheriv('aes-256-cbc', this.key, iv);
|
|
const decrypted = Buffer.concat([decipher.update(encryptedData), decipher.final()]);
|
|
return decrypted;
|
|
}
|
|
|
|
async encrypt(data: Buffer): Promise<void> {
|
|
const encryptedBuffer = this.encryptBuffer(data);
|
|
await fs.writeFile(this.filePath, encryptedBuffer);
|
|
}
|
|
|
|
async decrypt(): Promise<Buffer | null> {
|
|
try {
|
|
await fs.access(this.filePath);
|
|
} catch {
|
|
return null;
|
|
}
|
|
const buffer = await fs.readFile(this.filePath);
|
|
const decryptedData = this.decryptBuffer(buffer);
|
|
return decryptedData;
|
|
}
|
|
}
|