You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.6 KiB
62 lines
1.6 KiB
const request = require("superagent");
|
|
const fs = require("fs");
|
|
|
|
function isEncrypted(file) {
|
|
const magic = Buffer.from([0x00, 0x00, 0x5b, 0x00, 0xe5]);
|
|
|
|
if (file?.buffer && Buffer.isBuffer(file.buffer)) {
|
|
if (file.buffer.length < 5) {
|
|
return false;
|
|
}
|
|
return file.buffer.subarray(0, 5).equals(magic);
|
|
}
|
|
|
|
if (file?.path) {
|
|
const fd = fs.openSync(file.path, "r");
|
|
try {
|
|
const buffer = Buffer.alloc(5);
|
|
const bytesRead = fs.readSync(fd, buffer, 0, 5, 0);
|
|
if (bytesRead < 5) {
|
|
return false;
|
|
}
|
|
return buffer.equals(magic);
|
|
} finally {
|
|
fs.closeSync(fd);
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
module.exports.decryption = async (ctx, next) => {
|
|
try {
|
|
const { xunruan } = ctx.config;
|
|
const { file } = ctx.request;
|
|
const fileBuffer = file?.buffer || (file?.path ? fs.readFileSync(file.path) : null);
|
|
|
|
if (!fileBuffer) {
|
|
ctx.status = 400;
|
|
ctx.body = { message: "file is required." };
|
|
return;
|
|
}
|
|
|
|
if (!isEncrypted(file)) {
|
|
ctx.status = 200;
|
|
ctx.body = fileBuffer;
|
|
return;
|
|
}
|
|
|
|
let url = `${xunruan.host}/uploadSecret`;
|
|
let res_ = await request
|
|
.post(url)
|
|
.set("Content-Type", "application/octet-stream")
|
|
.send(fileBuffer)
|
|
.responseType("binary");
|
|
ctx.status = 200;
|
|
ctx.body = res_.body;
|
|
} catch (error) {
|
|
console.error(error, "error");
|
|
ctx.status = 400;
|
|
ctx.body = { message: "decryption error." };
|
|
}
|
|
};
|
|
|