Files
tap/lib/server/password.ts
T

50 lines
2.1 KiB
TypeScript
Raw 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.
import { randomBytes, scrypt as nativeScrypt, scryptSync, timingSafeEqual } from 'node:crypto';
const COST = 32768;
const OPTIONS = { N: COST, r: 8, p: 1, maxmem: 64 * 1024 * 1024 };
const KEY_LENGTH = 64;
// A nonempty, invalid hash also rejects password login on older compatible releases.
export const PASSWORD_LOGIN_DISABLED = '!feishu-only';
export function hasStoredPassword(hash: string | undefined): boolean {
return Boolean(hash) && hash !== PASSWORD_LOGIN_DISABLED;
}
export function validatePassword(password: unknown): asserts password is string {
if (typeof password !== 'string' || password.length < 12 || password.length > 128) {
throw new Error('密码须为 12–128 个字符。');
}
}
function derive(password: string, salt: Buffer): Promise<Buffer> {
return new Promise((resolve, reject) => {
nativeScrypt(password, salt, KEY_LENGTH, OPTIONS, (error, key) => error ? reject(error) : resolve(key));
});
}
function encode(salt: Buffer, key: Buffer): string {
return `scrypt$${COST}$8$1$${salt.toString('hex')}$${key.toString('hex')}`;
}
export async function hashPassword(password: string): Promise<string> {
validatePassword(password);
const salt = randomBytes(16);
return encode(salt, await derive(password, salt));
}
// Only used once while bootstrapping an empty database, within the startup transaction.
export function hashPasswordSync(password: string): string {
validatePassword(password);
const salt = randomBytes(16);
return encode(salt, scryptSync(password, salt, KEY_LENGTH, OPTIONS));
}
export async function verifyPassword(password: string, encoded: string): Promise<boolean> {
if (typeof password !== 'string' || password.length > 128) return false;
const parts = encoded.split('$');
if (parts.length !== 6 || parts[0] !== 'scrypt' || parts[1] !== String(COST) || parts[2] !== '8' || parts[3] !== '1') return false;
if (!/^[a-f0-9]{32}$/.test(parts[4]) || !/^[a-f0-9]{128}$/.test(parts[5])) return false;
const key = await derive(password, Buffer.from(parts[4], 'hex'));
return timingSafeEqual(key, Buffer.from(parts[5], 'hex'));
}