Inital commit
This commit is contained in:
commit
917effe259
30 files changed
+22019
No files matched your search
@@ -0,0 +1,54 @@
|
||||
import express from "express";
|
||||
import { basicAuth, CustomRequest } from "./utils";
|
||||
import { Encryptor } from "./encryptor";
|
||||
|
||||
export const api = express.Router();
|
||||
api.use(basicAuth as any);
|
||||
api.use((req, res, next) => {
|
||||
req.body = [];
|
||||
req.on('data', chunk => {
|
||||
req.body.push(chunk);
|
||||
});
|
||||
req.on('end', () => {
|
||||
req.body = Buffer.concat(req.body);
|
||||
next();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
api.get("/check", async (req: any, res: any) => {
|
||||
try {
|
||||
const r = req as CustomRequest;
|
||||
const result = await Encryptor.exist(r._user!.username, r._user!.password);
|
||||
return res.send(!!result);
|
||||
} catch (error) {
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
});
|
||||
|
||||
api.get("/:file", async (req: any, res: any) => {
|
||||
try {
|
||||
const r = req as CustomRequest;
|
||||
const en = await Encryptor.createEncryptor(r._user!.username, r._user!.password, r.params.file as string);
|
||||
const buffer = await en.decrypt();
|
||||
if (buffer) {
|
||||
res.send(buffer)
|
||||
} else {
|
||||
return res.sendStatus(404);
|
||||
}
|
||||
} catch (error) {
|
||||
return res.sendStatus(403);
|
||||
}
|
||||
});
|
||||
|
||||
api.post("/:file", async (req: any, res: any) => {
|
||||
try {
|
||||
const r = req as CustomRequest;
|
||||
const en = await Encryptor.createEncryptor(r._user!.username, r._user!.password, r.params.file as string);
|
||||
en.encrypt(req.body);
|
||||
return res.send(true);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return res.sendStatus(403);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Encryptor } from "./encryptor";
|
||||
import { readFileSync } from "fs";
|
||||
import * as path from "path";
|
||||
import express from "express";
|
||||
import { api } from "./api";
|
||||
|
||||
const config = JSON.parse(readFileSync(path.join(process.cwd(), "config.json"), "utf8")) as {
|
||||
PORT: number;
|
||||
VALIDATOR_STRING: string;
|
||||
};
|
||||
|
||||
Encryptor.setMagic(config.VALIDATOR_STRING);
|
||||
|
||||
const app = express();
|
||||
|
||||
app.disable('x-powered-by');
|
||||
app.use(express.static("build"));
|
||||
app.use((req, res, next) => {
|
||||
res.header('Access-Control-Allow-Origin', '*');
|
||||
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
|
||||
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
||||
if (req.method === 'OPTIONS') {
|
||||
return res.sendStatus(204); // Respond to preflight requests
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
|
||||
app.use("/api", api);
|
||||
|
||||
app.listen(config.PORT, () => {
|
||||
console.log(`Listening to ${config.PORT}`);
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { Encryptor } from "./encryptor";
|
||||
|
||||
export interface CustomRequest extends Request {
|
||||
_user?: { username: string; password: string };
|
||||
}
|
||||
|
||||
export function basicAuth(req: CustomRequest, res: Response, next: NextFunction) {
|
||||
const authHeader = req.headers['authorization'];
|
||||
|
||||
if (!authHeader) {
|
||||
return res.sendStatus(401);
|
||||
}
|
||||
|
||||
const base64Credentials = authHeader.split(' ')[1];
|
||||
const credentials = Buffer.from(base64Credentials, 'base64').toString('utf-8');
|
||||
const [username, password] = credentials.split(':');
|
||||
const safeString = Encryptor.makeFileSafeString(username);
|
||||
|
||||
if (safeString.length < 6) {
|
||||
return res.sendStatus(401);
|
||||
}
|
||||
|
||||
req._user = {
|
||||
username,
|
||||
password,
|
||||
}
|
||||
next();
|
||||
};
|
||||
Reference in new issue
Block a user