better-auth
Version:
The most comprehensive authentication framework for TypeScript.
1 lines • 1.93 kB
Source Map (JSON)
{"version":3,"file":"password.mjs","names":[],"sources":["../../src/crypto/password.ts"],"sourcesContent":["import { BetterAuthError } from \"@better-auth/core/error\";\nimport { hex } from \"@better-auth/utils/hex\";\nimport { scryptAsync } from \"@noble/hashes/scrypt.js\";\nimport { hexToBytes } from \"@noble/hashes/utils.js\";\nimport { constantTimeEqual } from \"./buffer\";\n\nconst config = {\n\tN: 16384,\n\tr: 16,\n\tp: 1,\n\tdkLen: 64,\n};\n\nasync function generateKey(password: string, salt: string) {\n\treturn await scryptAsync(password.normalize(\"NFKC\"), salt, {\n\t\tN: config.N,\n\t\tp: config.p,\n\t\tr: config.r,\n\t\tdkLen: config.dkLen,\n\t\tmaxmem: 128 * config.N * config.r * 2,\n\t});\n}\n\nexport const hashPassword = async (password: string) => {\n\tconst salt = hex.encode(crypto.getRandomValues(new Uint8Array(16)));\n\tconst key = await generateKey(password, salt);\n\treturn `${salt}:${hex.encode(key)}`;\n};\n\nexport const verifyPassword = async ({\n\thash,\n\tpassword,\n}: {\n\thash: string;\n\tpassword: string;\n}) => {\n\tconst [salt, key] = hash.split(\":\");\n\tif (!salt || !key) {\n\t\tthrow new BetterAuthError(\"Invalid password hash\");\n\t}\n\tconst targetKey = await generateKey(password, salt!);\n\treturn constantTimeEqual(targetKey, hexToBytes(key));\n};\n"],"mappings":";;;;;;;AAMA,MAAM,SAAS;CACd,GAAG;CACH,GAAG;CACH,GAAG;CACH,OAAO;CACP;AAED,eAAe,YAAY,UAAkB,MAAc;AAC1D,QAAO,MAAM,YAAY,SAAS,UAAU,OAAO,EAAE,MAAM;EAC1D,GAAG,OAAO;EACV,GAAG,OAAO;EACV,GAAG,OAAO;EACV,OAAO,OAAO;EACd,QAAQ,MAAM,OAAO,IAAI,OAAO,IAAI;EACpC,CAAC;;AAGH,MAAa,eAAe,OAAO,aAAqB;CACvD,MAAM,OAAO,IAAI,OAAO,OAAO,gBAAgB,IAAI,WAAW,GAAG,CAAC,CAAC;CACnE,MAAM,MAAM,MAAM,YAAY,UAAU,KAAK;AAC7C,QAAO,GAAG,KAAK,GAAG,IAAI,OAAO,IAAI;;AAGlC,MAAa,iBAAiB,OAAO,EACpC,MACA,eAIK;CACL,MAAM,CAAC,MAAM,OAAO,KAAK,MAAM,IAAI;AACnC,KAAI,CAAC,QAAQ,CAAC,IACb,OAAM,IAAI,gBAAgB,wBAAwB;AAGnD,QAAO,kBADW,MAAM,YAAY,UAAU,KAAM,EAChB,WAAW,IAAI,CAAC"}