24 lines
1.2 KiB
TypeScript
24 lines
1.2 KiB
TypeScript
import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
|
|
import { promisify } from "node:util";
|
|
|
|
// PIN der Kinder: scrypt mit Salz. Vier Ziffern sind wenig — die eigentliche
|
|
// Hürde ist das freigeschaltete Gerät (lib/auth/kids.ts) und die Bremse.
|
|
const run = promisify(scrypt) as (pw: string, salt: Buffer, len: number, opts: object) => Promise<Buffer>;
|
|
const OPTS = { N: 16384, r: 8, p: 1 };
|
|
|
|
export const isValidPin = (pin: string) => /^\d{4}$/.test(pin);
|
|
|
|
export async function hashPin(pin: string): Promise<string> {
|
|
const salt = randomBytes(16);
|
|
const hash = await run(pin, salt, 32, OPTS);
|
|
return `scrypt$${salt.toString("base64")}$${hash.toString("base64")}`;
|
|
}
|
|
|
|
export async function verifyPin(pin: string, stored: string | null): Promise<boolean> {
|
|
const [kind, salt, hash] = (stored ?? "").split("$");
|
|
// Ohne gespeicherte PIN trotzdem rechnen, damit die Antwortzeit nichts verrät.
|
|
const expected = kind === "scrypt" && salt && hash ? Buffer.from(hash, "base64") : Buffer.alloc(32);
|
|
const actual = await run(pin, salt ? Buffer.from(salt, "base64") : Buffer.alloc(16), 32, OPTS);
|
|
return kind === "scrypt" && expected.length === actual.length && timingSafeEqual(expected, actual);
|
|
}
|