brendmanager/src/owner.js

30 lines
1.4 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Код владельца: только с ним письмо можно одобрить и отметить отправленным (BRM-20).
// Источник — OWNER_CODE из окружения; если его нет, код задаётся при первом одобрении.
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
export const MIN_CODE = 6;
const same = (a, b) => a.length === b.length && crypto.timingSafeEqual(a, b);
export function createOwner(file, envCode) {
let saved = null;
try { saved = JSON.parse(fs.readFileSync(file, "utf8")); } catch {}
const hash = (code, salt) => crypto.scryptSync(code, salt, 32);
return {
isSet: () => !!envCode || !!saved,
/** @returns {"ok"|"wrong"|"short"} */
verify(input) {
const code = typeof input === "string" ? input : "";
if (envCode) return same(crypto.createHash("sha256").update(code).digest(), crypto.createHash("sha256").update(envCode).digest()) ? "ok" : "wrong";
if (saved) return same(hash(code, Buffer.from(saved.salt, "hex")), Buffer.from(saved.hash, "hex")) ? "ok" : "wrong";
if (code.length < MIN_CODE) return "short";
const salt = crypto.randomBytes(16);
saved = { salt: salt.toString("hex"), hash: hash(code, salt).toString("hex") };
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, JSON.stringify(saved));
return "ok";
},
};
}