umami/lib/crypto.js

45 lines
1.1 KiB
JavaScript
Raw Normal View History

2020-07-23 00:46:05 +02:00
import crypto from 'crypto';
2020-07-23 05:45:09 +02:00
import { v5 } from 'uuid';
import bcrypt from 'bcrypt';
2020-07-23 06:33:17 +02:00
import { JWT, JWE, JWK } from 'jose';
2020-07-23 00:46:05 +02:00
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/;
2020-07-23 06:33:17 +02:00
const KEY = JWK.asKey(Buffer.from(secret()));
2020-07-23 00:46:05 +02:00
2020-07-24 04:56:55 +02:00
export function hash(...args) {
return crypto.createHash('sha512').update(args.join('')).digest('hex');
2020-07-23 05:45:09 +02:00
}
export function secret() {
2020-07-24 04:56:55 +02:00
return hash(process.env.HASH_SALT);
2020-07-23 05:45:09 +02:00
}
2020-07-23 00:46:05 +02:00
2020-07-23 05:45:09 +02:00
export function uuid(...args) {
return v5(args.join(''), v5(process.env.HASH_SALT, v5.DNS));
2020-07-23 00:46:05 +02:00
}
2020-07-24 04:56:55 +02:00
export function isValidId(s) {
2020-07-23 00:46:05 +02:00
return UUID_REGEX.test(s);
}
2020-07-23 06:33:17 +02:00
export function checkPassword(password, hash) {
return bcrypt.compare(password, hash);
2020-07-23 00:46:05 +02:00
}
2020-07-23 06:33:17 +02:00
export async function createToken(payload) {
return JWT.sign(payload, KEY);
2020-07-23 00:46:05 +02:00
}
2020-07-23 06:33:17 +02:00
export async function verifyToken(token) {
return JWT.verify(token, KEY);
}
export async function createSecureToken(payload) {
return JWE.encrypt(await createToken(payload), KEY);
}
export async function verifySecureToken(token) {
const result = await JWE.decrypt(token, KEY);
return verifyToken(result.toString());
2020-07-23 00:46:05 +02:00
}