Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

feat: implement argon2 hashing algo (experimental)

thecodrr9a8db4b067f9
diff --git a/apps/web/public/argon2.wasm b/apps/web/public/argon2.wasm
new file mode 100644
index 000000000..f069ea8da
Binary files /dev/null and b/apps/web/public/argon2.wasm differ
diff --git a/apps/web/src/crypto/argon2-loader.js b/apps/web/src/crypto/argon2-loader.js
new file mode 100644
index 000000000..96debf0d8
--- /dev/null
+++ b/apps/web/src/crypto/argon2-loader.js
@@ -0,0 +1,766 @@
+const loader = `var Module = typeof self !== "undefined" && typeof self.Module !== "undefined" ? self.Module : {};
+var jsModule = Module;
+var moduleOverrides = {};
+var key;
+for (key in Module) {
+ if (Module.hasOwnProperty(key)) {
+ moduleOverrides[key] = Module[key];
+ }
+}
+var arguments_ = [];
+var thisProgram = "./this.program";
+var quit_ = function(status, toThrow) {
+ throw toThrow;
+};
+var ENVIRONMENT_IS_WEB = false;
+var ENVIRONMENT_IS_WORKER = false;
+var ENVIRONMENT_IS_NODE = false;
+var ENVIRONMENT_HAS_NODE = false;
+var ENVIRONMENT_IS_SHELL = false;
+ENVIRONMENT_IS_WEB = typeof window === "object";
+ENVIRONMENT_IS_WORKER = typeof importScripts === "function";
+ENVIRONMENT_HAS_NODE =
+ typeof process === "object" &&
+ typeof process.versions === "object" &&
+ typeof process.versions.node === "string";
+ENVIRONMENT_IS_NODE =
+ ENVIRONMENT_HAS_NODE && !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_WORKER;
+ENVIRONMENT_IS_SHELL =
+ !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
+var scriptDirectory = "";
+function locateFile(path) {
+ if (Module["locateFile"]) {
+ return Module["locateFile"](path, scriptDirectory);
+ }
+ return scriptDirectory + path;
+}
+var read_, readAsync, readBinary, setWindowTitle;
+var nodeFS;
+var nodePath;
+if (ENVIRONMENT_IS_NODE) {
+ scriptDirectory = __dirname + "/";
+ read_ = function shell_read(filename, binary) {
+ if (!nodeFS) nodeFS = require("fs");
+ if (!nodePath) nodePath = require("path");
+ filename = nodePath["normalize"](filename);
+ return nodeFS["readFileSync"](filename, binary ? null : "utf8");
+ };
+ readBinary = function readBinary(filename) {
+ var ret = read_(filename, true);
+ if (!ret.buffer) {
+ ret = new Uint8Array(ret);
+ }
+ assert(ret.buffer);
+ return ret;
+ };
+ if (process["argv"].length > 1) {
+ thisProgram = process["argv"][1];
+ }
+ arguments_ = process["argv"].slice(2);
+ if (typeof module !== "undefined") {
+ module["exports"] = Module;
+ }
+ process["on"]("uncaughtException", function(ex) {
+ if (!(ex instanceof ExitStatus)) {
+ throw ex;
+ }
+ });
+ process["on"]("unhandledRejection", abort);
+ quit_ = function(status) {
+ process["exit"](status);
+ };
+ Module["inspect"] = function() {
+ return "[Emscripten Module object]";
+ };
+} else if (ENVIRONMENT_IS_SHELL) {
+ if (typeof read != "undefined") {
+ read_ = function shell_read(f) {
+ return read(f);
+ };
+ }
+ readBinary = function readBinary(f) {
+ var data;
+ if (typeof readbuffer === "function") {
+ return new Uint8Array(readbuffer(f));
+ }
+ data = read(f, "binary");
+ assert(typeof data === "object");
+ return data;
+ };
+ if (typeof scriptArgs != "undefined") {
+ arguments_ = scriptArgs;
+ } else if (typeof arguments != "undefined") {
+ arguments_ = arguments;
+ }
+ if (typeof quit === "function") {
+ quit_ = function(status) {
+ quit(status);
+ };
+ }
+ if (typeof print !== "undefined") {
+ if (typeof console === "undefined") console = {};
+ console.log = print;
+ console.warn = console.error =
+ typeof printErr !== "undefined" ? printErr : print;
+ }
+} else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
+ if (ENVIRONMENT_IS_WORKER) {
+ scriptDirectory = self.location.href;
+ } else if (document.currentScript) {
+ scriptDirectory = document.currentScript.src;
+ }
+ if (scriptDirectory.indexOf("blob:") !== 0) {
+ scriptDirectory = scriptDirectory.substr(
+ 0,
+ scriptDirectory.lastIndexOf("/") + 1
+ );
+ } else {
+ scriptDirectory = "";
+ }
+ {
+ read_ = function shell_read(url) {
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", url, false);
+ xhr.send(null);
+ return xhr.responseText;
+ };
+ if (ENVIRONMENT_IS_WORKER) {
+ readBinary = function readBinary(url) {
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", url, false);
+ xhr.responseType = "arraybuffer";
+ xhr.send(null);
+ return new Uint8Array(xhr.response);
+ };
+ }
+ readAsync = function readAsync(url, onload, onerror) {
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", url, true);
+ xhr.responseType = "arraybuffer";
+ xhr.onload = function xhr_onload() {
+ if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) {
+ onload(xhr.response);
+ return;
+ }
+ onerror();
+ };
+ xhr.onerror = onerror;
+ xhr.send(null);
+ };
+ }
+ setWindowTitle = function(title) {
+ document.title = title;
+ };
+} else {
+}
+var out = Module["print"] || console.log.bind(console);
+var err = Module["printErr"] || console.warn.bind(console);
+for (key in moduleOverrides) {
+ if (moduleOverrides.hasOwnProperty(key)) {
+ Module[key] = moduleOverrides[key];
+ }
+}
+moduleOverrides = null;
+if (Module["arguments"]) arguments_ = Module["arguments"];
+if (Module["thisProgram"]) thisProgram = Module["thisProgram"];
+if (Module["quit"]) quit_ = Module["quit"];
+function dynamicAlloc(size) {
+ var ret = HEAP32[DYNAMICTOP_PTR >> 2];
+ var end = (ret + size + 15) & -16;
+ if (end > _emscripten_get_heap_size()) {
+ abort();
+ }
+ HEAP32[DYNAMICTOP_PTR >> 2] = end;
+ return ret;
+}
+function getNativeTypeSize(type) {
+ switch (type) {
+ case "i1":
+ case "i8":
+ return 1;
+ case "i16":
+ return 2;
+ case "i32":
+ return 4;
+ case "i64":
+ return 8;
+ case "float":
+ return 4;
+ case "double":
+ return 8;
+ default: {
+ if (type[type.length - 1] === "*") {
+ return 4;
+ } else if (type[0] === "i") {
+ var bits = parseInt(type.substr(1));
+ assert(
+ bits % 8 === 0,
+ "getNativeTypeSize invalid bits " + bits + ", type " + type
+ );
+ return bits / 8;
+ } else {
+ return 0;
+ }
+ }
+ }
+}
+var asm2wasmImports = {
+ "f64-rem": function(x, y) {
+ return x % y;
+ },
+ debugger: function() {}
+};
+var functionPointers = new Array(0);
+var wasmBinary;
+if (Module["wasmBinary"]) wasmBinary = Module["wasmBinary"];
+var noExitRuntime;
+if (Module["noExitRuntime"]) noExitRuntime = Module["noExitRuntime"];
+if (typeof WebAssembly !== "object") {
+ err("no native wasm support detected");
+}
+function setValue(ptr, value, type, noSafe) {
+ type = type || "i8";
+ if (type.charAt(type.length - 1) === "*") type = "i32";
+ switch (type) {
+ case "i1":
+ HEAP8[ptr >> 0] = value;
+ break;
+ case "i8":
+ HEAP8[ptr >> 0] = value;
+ break;
+ case "i16":
+ HEAP16[ptr >> 1] = value;
+ break;
+ case "i32":
+ HEAP32[ptr >> 2] = value;
+ break;
+ case "i64":
+ tempI64 = [
+ value >>> 0,
+ ((tempDouble = value),
+ +Math_abs(tempDouble) >= 1
+ ? tempDouble > 0
+ ? (Math_min(+Math_floor(tempDouble / 4294967296), 4294967295) |
+ 0) >>>
+ 0
+ : ~~+Math_ceil(
+ (tempDouble - +(~~tempDouble >>> 0)) / 4294967296
+ ) >>> 0
+ : 0)
+ ];
+ HEAP32[ptr >> 2] = tempI64[0];
+ HEAP32[(ptr + 4) >> 2] = tempI64[1];
+ break;
+ case "float":
+ HEAPF32[ptr >> 2] = value;
+ break;
+ case "double":
+ HEAPF64[ptr >> 3] = value;
+ break;
+ default:
+ abort("invalid type for setValue: " + type);
+ }
+}
+var wasmMemory;
+var wasmTable = new WebAssembly.Table({
+ initial: 9,
+ maximum: 9,
+ element: "anyfunc"
+});
+var ABORT = false;
+var EXITSTATUS = 0;
+function assert(condition, text) {
+ if (!condition) {
+ abort("Assertion failed: " + text);
+ }
+}
+var ALLOC_NORMAL = 0;
+var ALLOC_NONE = 3;
+function allocate(slab, types, allocator, ptr) {
+ var zeroinit, size;
+ if (typeof slab === "number") {
+ zeroinit = true;
+ size = slab;
+ } else {
+ zeroinit = false;
+ size = slab.length;
+ }
+ var singleType = typeof types === "string" ? types : null;
+ var ret;
+ if (allocator == ALLOC_NONE) {
+ ret = ptr;
+ } else {
+ ret = [_malloc, stackAlloc, dynamicAlloc][allocator](
+ Math.max(size, singleType ? 1 : types.length)
+ );
+ }
+ if (zeroinit) {
+ var stop;
+ ptr = ret;
+ assert((ret & 3) == 0);
+ stop = ret + (size & ~3);
+ for (; ptr < stop; ptr += 4) {
+ HEAP32[ptr >> 2] = 0;
+ }
+ stop = ret + size;
+ while (ptr < stop) {
+ HEAP8[ptr++ >> 0] = 0;
+ }
+ return ret;
+ }
+ if (singleType === "i8") {
+ if (slab.subarray || slab.slice) {
+ HEAPU8.set(slab, ret);
+ } else {
+ HEAPU8.set(new Uint8Array(slab), ret);
+ }
+ return ret;
+ }
+ var i = 0,
+ type,
+ typeSize,
+ previousType;
+ while (i < size) {
+ var curr = slab[i];
+ type = singleType || types[i];
+ if (type === 0) {
+ i++;
+ continue;
+ }
+ if (type == "i64") type = "i32";
+ setValue(ret + i, curr, type);
+ if (previousType !== type) {
+ typeSize = getNativeTypeSize(type);
+ previousType = type;
+ }
+ i += typeSize;
+ }
+ return ret;
+}
+var UTF8Decoder =
+ typeof TextDecoder !== "undefined" ? new TextDecoder("utf8") : undefined;
+function UTF8ArrayToString(u8Array, idx, maxBytesToRead) {
+ var endIdx = idx + maxBytesToRead;
+ var endPtr = idx;
+ while (u8Array[endPtr] && !(endPtr >= endIdx)) ++endPtr;
+ if (endPtr - idx > 16 && u8Array.subarray && UTF8Decoder) {
+ return UTF8Decoder.decode(u8Array.subarray(idx, endPtr));
+ } else {
+ var str = "";
+ while (idx < endPtr) {
+ var u0 = u8Array[idx++];
+ if (!(u0 & 128)) {
+ str += String.fromCharCode(u0);
+ continue;
+ }
+ var u1 = u8Array[idx++] & 63;
+ if ((u0 & 224) == 192) {
+ str += String.fromCharCode(((u0 & 31) << 6) | u1);
+ continue;
+ }
+ var u2 = u8Array[idx++] & 63;
+ if ((u0 & 240) == 224) {
+ u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;
+ } else {
+ u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (u8Array[idx++] & 63);
+ }
+ if (u0 < 65536) {
+ str += String.fromCharCode(u0);
+ } else {
+ var ch = u0 - 65536;
+ str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023));
+ }
+ }
+ }
+ return str;
+}
+function UTF8ToString(ptr, maxBytesToRead) {
+ return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : "";
+}
+var UTF16Decoder =
+ typeof TextDecoder !== "undefined" ? new TextDecoder("utf-16le") : undefined;
+var WASM_PAGE_SIZE = 65536;
+function alignUp(x, multiple) {
+ if (x % multiple > 0) {
+ x += multiple - (x % multiple);
+ }
+ return x;
+}
+var buffer, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
+function updateGlobalBufferAndViews(buf) {
+ buffer = buf;
+ Module["HEAP8"] = HEAP8 = new Int8Array(buf);
+ Module["HEAP16"] = HEAP16 = new Int16Array(buf);
+ Module["HEAP32"] = HEAP32 = new Int32Array(buf);
+ Module["HEAPU8"] = HEAPU8 = new Uint8Array(buf);
+ Module["HEAPU16"] = HEAPU16 = new Uint16Array(buf);
+ Module["HEAPU32"] = HEAPU32 = new Uint32Array(buf);
+ Module["HEAPF32"] = HEAPF32 = new Float32Array(buf);
+ Module["HEAPF64"] = HEAPF64 = new Float64Array(buf);
+}
+var DYNAMIC_BASE = 5248512,
+ DYNAMICTOP_PTR = 5440;
+var INITIAL_TOTAL_MEMORY = Module["TOTAL_MEMORY"] || 16777216;
+if (Module["wasmMemory"]) {
+ wasmMemory = Module["wasmMemory"];
+} else {
+ wasmMemory = new WebAssembly.Memory({
+ initial: INITIAL_TOTAL_MEMORY / WASM_PAGE_SIZE,
+ maximum: 2147418112 / WASM_PAGE_SIZE
+ });
+}
+if (wasmMemory) {
+ buffer = wasmMemory.buffer;
+}
+INITIAL_TOTAL_MEMORY = buffer.byteLength;
+updateGlobalBufferAndViews(buffer);
+HEAP32[DYNAMICTOP_PTR >> 2] = DYNAMIC_BASE;
+function callRuntimeCallbacks(callbacks) {
+ while (callbacks.length > 0) {
+ var callback = callbacks.shift();
+ if (typeof callback == "function") {
+ callback();
+ continue;
+ }
+ var func = callback.func;
+ if (typeof func === "number") {
+ if (callback.arg === undefined) {
+ Module["dynCall_v"](func);
+ } else {
+ Module["dynCall_vi"](func, callback.arg);
+ }
+ } else {
+ func(callback.arg === undefined ? null : callback.arg);
+ }
+ }
+}
+var __ATPRERUN__ = [];
+var __ATINIT__ = [];
+var __ATMAIN__ = [];
+var __ATPOSTRUN__ = [];
+var runtimeInitialized = false;
+function preRun() {
+ if (Module["preRun"]) {
+ if (typeof Module["preRun"] == "function")
+ Module["preRun"] = [Module["preRun"]];
+ while (Module["preRun"].length) {
+ addOnPreRun(Module["preRun"].shift());
+ }
+ }
+ callRuntimeCallbacks(__ATPRERUN__);
+}
+function initRuntime() {
+ runtimeInitialized = true;
+ callRuntimeCallbacks(__ATINIT__);
+}
+function preMain() {
+ callRuntimeCallbacks(__ATMAIN__);
+}
+function postRun() {
+ if (Module["postRun"]) {
+ if (typeof Module["postRun"] == "function")
+ Module["postRun"] = [Module["postRun"]];
+ while (Module["postRun"].length) {
+ addOnPostRun(Module["postRun"].shift());
+ }
+ }
+ callRuntimeCallbacks(__ATPOSTRUN__);
+}
+function addOnPreRun(cb) {
+ __ATPRERUN__.unshift(cb);
+}
+function addOnPostRun(cb) {
+ __ATPOSTRUN__.unshift(cb);
+}
+var Math_abs = Math.abs;
+var Math_ceil = Math.ceil;
+var Math_floor = Math.floor;
+var Math_min = Math.min;
+var runDependencies = 0;
+var runDependencyWatcher = null;
+var dependenciesFulfilled = null;
+function addRunDependency(id) {
+ runDependencies++;
+ if (Module["monitorRunDependencies"]) {
+ Module["monitorRunDependencies"](runDependencies);
+ }
+}
+function removeRunDependency(id) {
+ runDependencies--;
+ if (Module["monitorRunDependencies"]) {
+ Module["monitorRunDependencies"](runDependencies);
+ }
+ if (runDependencies == 0) {
+ if (runDependencyWatcher !== null) {
+ clearInterval(runDependencyWatcher);
+ runDependencyWatcher = null;
+ }
+ if (dependenciesFulfilled) {
+ var callback = dependenciesFulfilled;
+ dependenciesFulfilled = null;
+ callback();
+ }
+ }
+}
+Module["preloadedImages"] = {};
+Module["preloadedAudios"] = {};
+function abort(what) {
+ if (Module["onAbort"]) {
+ Module["onAbort"](what);
+ }
+ what += "";
+ out(what);
+ err(what);
+ ABORT = true;
+ EXITSTATUS = 1;
+ what = "abort(" + what + "). Build with -s ASSERTIONS=1 for more info.";
+ throw new WebAssembly.RuntimeError(what);
+}
+var dataURIPrefix = "data:application/octet-stream;base64,";
+function isDataURI(filename) {
+ return String.prototype.startsWith
+ ? filename.startsWith(dataURIPrefix)
+ : filename.indexOf(dataURIPrefix) === 0;
+}
+var wasmBinaryFile = "argon2.wasm";
+if (!isDataURI(wasmBinaryFile)) {
+ wasmBinaryFile = locateFile(wasmBinaryFile);
+}
+function getBinary() {
+ try {
+ if (wasmBinary) {
+ return new Uint8Array(wasmBinary);
+ }
+ if (readBinary) {
+ return readBinary(wasmBinaryFile);
+ } else {
+ throw "both async and sync fetching of the wasm failed";
+ }
+ } catch (err) {
+ abort(err);
+ }
+}
+function getBinaryPromise() {
+ if (
+ !wasmBinary &&
+ (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) &&
+ typeof fetch === "function"
+ ) {
+ return fetch(wasmBinaryFile, { credentials: "same-origin" })
+ .then(function(response) {
+ if (!response["ok"]) {
+ throw "failed to load wasm binary file at '" + wasmBinaryFile + "'";
+ }
+ return response["arrayBuffer"]();
+ })
+ .catch(function() {
+ return getBinary();
+ });
+ }
+ return new Promise(function(resolve, reject) {
+ resolve(getBinary());
+ });
+}
+function createWasm() {
+ var info = {
+ env: asmLibraryArg,
+ wasi_unstable: asmLibraryArg,
+ global: { NaN: NaN, Infinity: Infinity },
+ "global.Math": Math,
+ asm2wasm: asm2wasmImports
+ };
+ function receiveInstance(instance, module) {
+ var exports = instance.exports;
+ Module["asm"] = exports;
+ removeRunDependency("wasm-instantiate");
+ }
+ addRunDependency("wasm-instantiate");
+ function receiveInstantiatedSource(output) {
+ Module = jsModule;
+ if (typeof self !== "undefined") self.Module = Module;
+ receiveInstance(output["instance"]);
+ }
+ function instantiateArrayBuffer(receiver) {
+ return getBinaryPromise()
+ .then(function(binary) {
+ return WebAssembly.instantiate(binary, info);
+ })
+ .then(receiver, function(reason) {
+ err("failed to asynchronously prepare wasm: " + reason);
+ abort(reason);
+ });
+ }
+ function instantiateAsync() {
+ if (
+ !wasmBinary &&
+ typeof WebAssembly.instantiateStreaming === "function" &&
+ !isDataURI(wasmBinaryFile) &&
+ typeof fetch === "function"
+ ) {
+ fetch(wasmBinaryFile, { credentials: "same-origin" }).then(function(
+ response
+ ) {
+ var result = WebAssembly.instantiateStreaming(response, info);
+ return result.then(receiveInstantiatedSource, function(reason) {
+ err("wasm streaming compile failed: " + reason);
+ err("falling back to ArrayBuffer instantiation");
+ instantiateArrayBuffer(receiveInstantiatedSource);
+ });
+ });
+ } else {
+ return instantiateArrayBuffer(receiveInstantiatedSource);
+ }
+ }
+ if (Module["instantiateWasm"]) {
+ try {
+ var exports = Module["instantiateWasm"](info, receiveInstance);
+ return exports;
+ } catch (e) {
+ err("Module.instantiateWasm callback failed with error: " + e);
+ return false;
+ }
+ }
+ instantiateAsync();
+ return {};
+}
+Module["asm"] = createWasm;
+var tempDouble;
+var tempI64;
+function _emscripten_get_heap_size() {
+ return HEAP8.length;
+}
+function emscripten_realloc_buffer(size) {
+ try {
+ wasmMemory.grow((size - buffer.byteLength + 65535) >> 16);
+ updateGlobalBufferAndViews(wasmMemory.buffer);
+ return 1;
+ } catch (e) {}
+}
+function _emscripten_resize_heap(requestedSize) {
+ var oldSize = _emscripten_get_heap_size();
+ var PAGE_MULTIPLE = 65536;
+ var LIMIT = 2147483648 - PAGE_MULTIPLE;
+ if (requestedSize > LIMIT) {
+ return false;
+ }
+ var MIN_TOTAL_MEMORY = 16777216;
+ var newSize = Math.max(oldSize, MIN_TOTAL_MEMORY);
+ while (newSize < requestedSize) {
+ if (newSize <= 536870912) {
+ newSize = alignUp(2 * newSize, PAGE_MULTIPLE);
+ } else {
+ newSize = Math.min(
+ alignUp((3 * newSize + 2147483648) / 4, PAGE_MULTIPLE),
+ LIMIT
+ );
+ }
+ }
+ newSize = Math.min(newSize, 2147418112);
+ if (newSize == oldSize) {
+ return false;
+ }
+ var replacement = emscripten_realloc_buffer(newSize);
+ if (!replacement) {
+ return false;
+ }
+ return true;
+}
+function _emscripten_memcpy_big(dest, src, num) {
+ HEAPU8.set(HEAPU8.subarray(src, src + num), dest);
+}
+function _pthread_join() {}
+var asmGlobalArg = {};
+var asmLibraryArg = {
+ __memory_base: 1024,
+ __table_base: 0,
+ e: _emscripten_get_heap_size,
+ d: _emscripten_memcpy_big,
+ c: _emscripten_resize_heap,
+ b: _pthread_join,
+ a: abort,
+ memory: wasmMemory,
+ table: wasmTable
+};
+var asm = Module["asm"](asmGlobalArg, asmLibraryArg, buffer);
+Module["asm"] = asm;
+var _argon2_error_message = (Module["_argon2_error_message"] = function() {
+ return Module["asm"]["f"].apply(null, arguments);
+});
+var _argon2_hash = (Module["_argon2_hash"] = function() {
+ return Module["asm"]["g"].apply(null, arguments);
+});
+var _argon2_verify = (Module["_argon2_verify"] = function() {
+ return Module["asm"]["h"].apply(null, arguments);
+});
+var _free = (Module["_free"] = function() {
+ return Module["asm"]["i"].apply(null, arguments);
+});
+var _malloc = (Module["_malloc"] = function() {
+ return Module["asm"]["j"].apply(null, arguments);
+});
+var stackAlloc = (Module["stackAlloc"] = function() {
+ return Module["asm"]["k"].apply(null, arguments);
+});
+Module["asm"] = asm;
+Module["allocate"] = allocate;
+Module["UTF8ToString"] = UTF8ToString;
+Module["ALLOC_NORMAL"] = ALLOC_NORMAL;
+var calledRun;
+function ExitStatus(status) {
+ this.name = "ExitStatus";
+ this.message = "Program terminated with exit(" + status + ")";
+ this.status = status;
+}
+dependenciesFulfilled = function runCaller() {
+ if (!calledRun) run();
+ if (!calledRun) dependenciesFulfilled = runCaller;
+};
+function run(args) {
+ args = args || arguments_;
+ if (runDependencies > 0) {
+ return;
+ }
+ preRun();
+ if (runDependencies > 0) return;
+ function doRun() {
+ if (calledRun) return;
+ calledRun = true;
+ if (ABORT) return;
+ initRuntime();
+ preMain();
+ if (Module["onRuntimeInitialized"]) Module["onRuntimeInitialized"]();
+ postRun();
+ }
+ if (Module["setStatus"]) {
+ Module["setStatus"]("Running...");
+ setTimeout(function() {
+ setTimeout(function() {
+ Module["setStatus"]("");
+ }, 1);
+ doRun();
+ }, 1);
+ } else {
+ doRun();
+ }
+}
+Module["run"] = run;
+if (Module["preInit"]) {
+ if (typeof Module["preInit"] == "function")
+ Module["preInit"] = [Module["preInit"]];
+ while (Module["preInit"].length > 0) {
+ Module["preInit"].pop()();
+ }
+}
+noExitRuntime = true;
+run();
+if (typeof module !== "undefined") module.exports = Module;
+Module.unloadRuntime = function() {
+ if (typeof self !== "undefined") {
+ delete self.Module;
+ }
+ Module = jsModule = wasmMemory = wasmTable = asm = buffer = HEAP8 = HEAPU8 = HEAP16 = HEAPU16 = HEAP32 = HEAPU32 = HEAPF32 = HEAPF64 = undefined;
+ if (typeof module !== "undefined") {
+ delete module.exports;
+ }
+};`;
+export default loader;
diff --git a/apps/web/src/crypto/argon2.js b/apps/web/src/crypto/argon2.js
new file mode 100644
index 000000000..c1bfe12ba
--- /dev/null
+++ b/apps/web/src/crypto/argon2.js
@@ -0,0 +1,252 @@
+const logger = console;
+const isDesktop = !!(
+ window.process &&
+ window.process.versions &&
+ window.process.versions.electron
+);
+const canUseWasmInWebWorker =
+ !isDesktop && !/Chrome/.test(navigator.appVersion);
+const Argon2 = {
+ argon2(
+ password,
+ salt,
+ memory,
+ iterations,
+ length,
+ parallelism,
+ type,
+ version
+ ) {
+ const args = {
+ password,
+ salt,
+ memory,
+ iterations,
+ length,
+ parallelism,
+ type,
+ version
+ };
+ return this.loadRuntime(memory).then(runtime => {
+ //const ts = //logger.ts();
+ return runtime.hash(args).then(hash => {
+ // logger.debug("Hash computed", logger.ts(ts));
+ return hash;
+ });
+ });
+ },
+
+ loadRuntime(requiredMemory) {
+ if (this.runtimeModule) {
+ return Promise.resolve(this.runtimeModule);
+ }
+ if (!global.WebAssembly) {
+ return Promise.reject("WebAssembly is not supported");
+ }
+ return new Promise((resolve, reject) => {
+ const loadTimeout = setTimeout(() => reject("timeout"), 5000);
+ try {
+ //const ts = //logger.ts();
+ const argon2LoaderCode = require("./argon2-loader").default;
+ //const wasmBinaryBase64 = require("./argon2-wasm").default;
+
+ const KB = 1024 * 1024;
+ const MB = 1024 * KB;
+ const GB = 1024 * MB;
+ const WASM_PAGE_SIZE = 64 * 1024;
+ const totalMemory = (2 * GB - 64 * KB) / 1024 / WASM_PAGE_SIZE;
+ const initialMemory = Math.min(
+ Math.max(Math.ceil((requiredMemory * 1024) / WASM_PAGE_SIZE), 256) +
+ 256,
+ totalMemory
+ );
+
+ if (canUseWasmInWebWorker) {
+ console.log("web worker");
+ const memoryDecl = `var wasmMemory=new WebAssembly.Memory({initial:${initialMemory},maximum:${totalMemory}});`;
+ const moduleDecl =
+ "var Module={" +
+ 'wasmJSMethod: "native-wasm",' +
+ 'wasmBinaryFile: "argon2.wasm",' +
+ "locateFile: (path) => { return path; }," +
+ 'print(...args) { postMessage({op:"log",args}) },' +
+ 'printErr(...args) { postMessage({op:"log",args}) },' +
+ "postRun:" +
+ this.workerPostRun.toString() +
+ "," +
+ "calcHash:" +
+ this.calcHash.toString() +
+ "," +
+ "wasmMemory:wasmMemory," +
+ "buffer:wasmMemory.buffer," +
+ "TOTAL_MEMORY:" +
+ initialMemory * WASM_PAGE_SIZE +
+ "}";
+ const script = argon2LoaderCode.replace(
+ /^var Module.*?}/,
+ memoryDecl + moduleDecl
+ );
+ console.log(script);
+ const blob = new Blob([script], { type: "application/javascript" });
+ const objectUrl = URL.createObjectURL(blob);
+ const worker = new Worker(objectUrl);
+ const onMessage = e => {
+ switch (e.data.op) {
+ case "log":
+ logger.debug(...e.data.args);
+ break;
+ case "postRun":
+ logger.debug(
+ "WebAssembly runtime loaded (web worker)"
+ //logger.ts(ts)
+ );
+ URL.revokeObjectURL(objectUrl);
+ clearTimeout(loadTimeout);
+ worker.removeEventListener("message", onMessage);
+ this.runtimeModule = {
+ hash(args) {
+ return new Promise((resolve, reject) => {
+ worker.postMessage(args);
+ const onHashMessage = e => {
+ worker.removeEventListener("message", onHashMessage);
+ worker.terminate();
+ Argon2.runtimeModule = null;
+ if (!e.data || e.data.error || !e.data.hash) {
+ const ex =
+ (e.data && e.data.error) || "unexpected error";
+ logger.error("Worker error", ex);
+ reject(ex);
+ } else {
+ resolve(e.data.hash);
+ }
+ };
+ worker.addEventListener("message", onHashMessage);
+ });
+ }
+ };
+ resolve(this.runtimeModule);
+ break;
+ default:
+ logger.error("Unknown message", e.data);
+ URL.revokeObjectURL(objectUrl);
+ reject("Load error");
+ }
+ };
+ worker.addEventListener("message", onMessage);
+ } else {
+ // Chrome and Electron crash if we use WASM in WebWorker
+ // see https://github.com/keeweb/keeweb/issues/1263
+ const wasmMemory = new WebAssembly.Memory({
+ initial: initialMemory,
+ maximum: totalMemory
+ });
+ global.Module = {
+ wasmJSMethod: "native-wasm",
+ locateFile: path => {
+ return path;
+ },
+ wasmBinaryFile: "argon2.wasm",
+ print(...args) {
+ logger.debug(...args);
+ },
+ printErr(...args) {
+ logger.debug(...args);
+ },
+ postRun: () => {
+ logger.debug(
+ "WebAssembly runtime loaded (main thread)"
+ //logger.ts(ts)
+ );
+ clearTimeout(loadTimeout);
+ resolve({
+ hash: args => {
+ const hash = this.calcHash(global.Module, args);
+ global.Module.unloadRuntime();
+ global.Module = undefined;
+ return Promise.resolve(hash);
+ }
+ });
+ },
+ wasmMemory,
+ buffer: wasmMemory.buffer,
+ TOTAL_MEMORY: initialMemory * WASM_PAGE_SIZE
+ };
+ // eslint-disable-next-line no-eval
+ eval(argon2LoaderCode);
+ }
+ } catch (err) {
+ reject(err);
+ }
+ }).catch(err => {
+ logger.warn("WebAssembly error", err);
+ throw new Error("WebAssembly error");
+ });
+ },
+
+ // eslint-disable-next-line object-shorthand
+ /* eslint-disable no-restricted-globals */
+ workerPostRun: function() {
+ self.postMessage({ op: "postRun" });
+ self.onmessage = e => {
+ try {
+ /* eslint-disable-next-line no-undef */
+ const hash = Module.calcHash(Module, e.data);
+ self.postMessage({ hash });
+ } catch (e) {
+ self.postMessage({ error: e.toString() });
+ }
+ };
+ },
+ /* eslint-enable no-restricted-globals */
+
+ // eslint-disable-next-line object-shorthand
+ calcHash: function(Module, args) {
+ let { password, salt } = args;
+ const { memory, iterations, length, parallelism, type, version } = args;
+ const passwordLen = password.byteLength;
+ password = Module.allocate(
+ new Uint8Array(password),
+ "i8",
+ Module.ALLOC_NORMAL
+ );
+ const saltLen = salt.byteLength;
+ salt = Module.allocate(new Uint8Array(salt), "i8", Module.ALLOC_NORMAL);
+ const hash = Module.allocate(new Array(length), "i8", Module.ALLOC_NORMAL);
+ const encodedLen = 512;
+ const encoded = Module.allocate(
+ new Array(encodedLen),
+ "i8",
+ Module.ALLOC_NORMAL
+ );
+
+ const res = Module._argon2_hash(
+ iterations,
+ memory,
+ parallelism,
+ password,
+ passwordLen,
+ salt,
+ saltLen,
+ hash,
+ length,
+ encoded,
+ encodedLen,
+ type,
+ version
+ );
+ if (res) {
+ throw new Error("Argon2 error " + res);
+ }
+ const hashArr = new Uint8Array(length);
+ for (let i = 0; i < length; i++) {
+ hashArr[i] = Module.HEAP8[hash + i];
+ }
+ Module._free(password);
+ Module._free(salt);
+ Module._free(hash);
+ Module._free(encoded);
+ return hashArr;
+ }
+};
+
+export default Argon2;
diff --git a/apps/web/src/interfaces/storage.js b/apps/web/src/interfaces/storage.js
index 74fe6e542..7fdd3daf5 100644
--- a/apps/web/src/interfaces/storage.js
+++ b/apps/web/src/interfaces/storage.js
@@ -1,6 +1,7 @@
import localforage from "localforage";
import { encode, decode } from "../utils/base64";
import { hexToBuffer, bufferToHex } from "../utils/hex";
+
const encoder = new TextEncoder();
const decoder = new TextDecoder();
diff --git a/apps/web/yarn.lock b/apps/web/yarn.lock
index 34327ea86..5dd61947c 100644
--- a/apps/web/yarn.lock
+++ b/apps/web/yarn.lock
@@ -3099,11 +3099,6 @@ crypto-browserify@^3.11.0:
randombytes "^2.0.0"
randomfill "^1.0.3"
-crypto-js@^4.0.0:
- version "4.0.0"
- resolved "https://registry.yarnpkg.com/crypto-js/-/crypto-js-4.0.0.tgz#2904ab2677a9d042856a2ea2ef80de92e4a36dcc"
- integrity sha512-bzHZN8Pn+gS7DQA6n+iUmBfl0hO5DJq++QP3U6uTucDtk/0iGpXd/Gg7CGR0p8tJhofJyaKoWBuJI4eAO00BBg==
-
css-blank-pseudo@^0.1.4:
version "0.1.4"
resolved "https://registry.yarnpkg.com/css-blank-pseudo/-/css-blank-pseudo-0.1.4.tgz#dfdefd3254bf8a82027993674ccf35483bfcb3c5"