@opengis/fastify-table
Version:
core-plugins
64 lines (63 loc) • 2.46 kB
JavaScript
import { createHmac, scrypt, randomBytes } from "node:crypto";
import util from "node:util";
import config from "../../../../config.js";
const scryptAsync = util.promisify(scrypt);
const { jwtSecret = "65450754381cfaf768eeb4bb33326529b48a40ffdb6e15d84dc224dff527166f", } = config.auth || {};
const jwtHeader = Buffer.from(JSON.stringify({
alg: "HS256",
typ: "JWT",
})).toString("base64");
export async function scryptHash(code) {
const salt = randomBytes(16).toString("hex");
const derived = (await scryptAsync(code, salt, 64)); // 64 bytes
return `${salt}:${derived.toString("hex")}`;
}
export async function scryptVerify(stored, code) {
const [salt, keyHex] = stored.split(":");
const derived = (await scryptAsync(code, salt, 64));
return keyHex === derived.toString("hex");
}
export function sign(uid, secret = jwtSecret, exp = 90000) {
if (typeof uid !== "string")
throw new Error("uid must be a string");
if (secret && typeof secret !== "string")
throw new Error("secret must be a string");
if (typeof exp !== "number")
throw new Error("exp must be a number");
const jwtPayload = Buffer.from(JSON.stringify({
uid,
exp,
created: Date.now(),
})).toString("base64");
const jwtEncrypted = [jwtHeader, jwtPayload].join(".");
const signature = createHmac("sha256", secret)
.update(jwtEncrypted)
.digest("base64");
return `${jwtEncrypted}.${signature}`;
}
export function verify(token, secret = jwtSecret) {
if (!token)
throw new Error("not enough params: token");
if (!secret)
throw new Error("not enough params: secret");
const split = token.split(".");
const signature = split[2];
try {
const header = JSON.parse(Buffer.from(split[0], "base64").toString());
const payload = JSON.parse(Buffer.from(split[1], "base64").toString());
const jwtHeader = Buffer.from(JSON.stringify(header)).toString("base64");
const jwtPayload = Buffer.from(JSON.stringify(payload)).toString("base64");
const jwtEncryptedExpected = [jwtHeader, jwtPayload].join(".");
const expectedSignature = createHmac("sha256", secret)
.update(jwtEncryptedExpected)
.digest("base64");
if (signature === expectedSignature) {
return true;
}
return false;
}
catch (err) {
return false;
}
}
export default null;