Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion apps/pwa/src/lib/crypto.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,14 @@ export function hashPassword(password) {

export function verifyPassword(password, stored) {
if (!stored || !stored.startsWith("scrypt$")) return false;
const [, saltHex, hashHex] = stored.split("$");
const parts = stored.split("$");
if (parts.length !== 3) return false;
const [, saltHex, hashHex] = parts;
if (!/^[0-9a-f]+$/i.test(saltHex) || !/^[0-9a-f]+$/i.test(hashHex)) return false;
if (saltHex.length % 2 !== 0 || hashHex.length % 2 !== 0) return false;
const salt = Buffer.from(saltHex, "hex");
const expected = Buffer.from(hashHex, "hex");
if (salt.length === 0 || expected.length === 0) return false;
const dk = crypto.scryptSync(String(password), salt, expected.length);
return dk.length === expected.length && crypto.timingSafeEqual(dk, expected);
}
Expand Down
22 changes: 22 additions & 0 deletions apps/pwa/test/password-hash.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import assert from "node:assert/strict";
import test from "node:test";
import { hashPassword, verifyPassword } from "../src/lib/crypto.mjs";

test("verifyPassword accepts a matching scrypt password hash", () => {
const stored = hashPassword("correct horse");

assert.equal(verifyPassword("correct horse", stored), true);
assert.equal(verifyPassword("wrong horse", stored), false);
});

test("verifyPassword rejects malformed scrypt hashes", () => {
for (const stored of [
"scrypt$00$",
"scrypt$00$nothex",
"scrypt$zz$aa",
"scrypt$0$aa",
"scrypt$00$aa$extra",
]) {
assert.equal(verifyPassword("anything", stored), false, stored);
}
});
Loading