CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/backend/auth/password-hash.ts
Views: 687
1
import { generate, verify } from "password-hash";
2
import LRU from "lru-cache";
3
4
// We cache computation of the hash, since e.g., api keys have the
5
// hash computed for every single api call, and it's always the same key,
6
// so that's expensive.
7
const cache = new LRU<string, string>({
8
max: 1000,
9
ttl: 1000 * 60 * 5, // 5 minutes
10
});
11
12
// You can change the parameters at any time and no existing passwords
13
// or cookies should break. This will only impact newly created
14
// passwords and cookies. Old ones can be read just fine (with the old
15
// parameters).
16
const HASH_ALGORITHM = "sha512";
17
const HASH_ITERATIONS = 1000;
18
const HASH_SALT_LENGTH = 32;
19
20
export default function passwordHash(password: string): string {
21
// This blocks the server for around 5ms.
22
// There are newer async libraries as explained at https://www.npmjs.com/package/password-hash
23
// that do NOT block, which maybe we should be using instead....
24
if (cache.has(password)) {
25
return cache.get(password)!;
26
}
27
28
const hash = generate(password, {
29
algorithm: HASH_ALGORITHM,
30
saltLength: HASH_SALT_LENGTH,
31
iterations: HASH_ITERATIONS,
32
});
33
cache.set(password, hash);
34
return hash;
35
}
36
37
export { verify as verifyPassword };
38
39