Skip to content

Commit

Permalink
Argon2: avoid loading multiple wasm modules on first initialisation (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
larabr committed Nov 21, 2023
1 parent a642edf commit d1550c5
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 12 deletions.
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@
"@rollup/plugin-replace": "^2.3.2",
"@rollup/plugin-wasm": "^6.1.2",
"@types/chai": "^4.2.14",
"argon2id": "^1.0.0",
"argon2id": "^1.0.1",
"benchmark": "^2.1.4",
"bn.js": "^4.11.8",
"chai": "^4.3.6",
Expand Down
11 changes: 7 additions & 4 deletions src/type/s2k/argon2.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,12 @@ class Argon2S2K {
const decodedM = 2 << (this.encodedM - 1);

try {
if (!argon2Promise) { // first load
loadArgonWasmModule = loadArgonWasmModule || (await import('argon2id')).default;
argon2Promise = loadArgonWasmModule();
}
// on first load, the argon2 lib is imported and the WASM module is initialized.
// the two steps need to be atomic to avoid race conditions causing multiple wasm modules
// being loaded when `argon2Promise` is not initialized.
loadArgonWasmModule = loadArgonWasmModule || (await import('argon2id')).default;
argon2Promise = argon2Promise || loadArgonWasmModule();

// important to keep local ref to argon2 in case the module is reloaded by another instance
const argon2 = await argon2Promise;

Expand All @@ -114,6 +116,7 @@ class Argon2S2K {
if (decodedM > ARGON2_WASM_MEMORY_THRESHOLD_RELOAD) {
// it will be awaited if needed at the next `produceKey` invocation
argon2Promise = loadArgonWasmModule();
argon2Promise.catch(() => {});
}
return hash;
} catch (e) {
Expand Down

0 comments on commit d1550c5

Please sign in to comment.