ssh2 icon indicating copy to clipboard operation
ssh2 copied to clipboard

Pure JS fallback when WASM is not available

Open mzoliker opened this issue 1 year ago • 1 comments

Hi,

Thank you for this wonderful library. I have a suggestion to make it even more wonderful :-).

Would it be possible to add a pure javascript fallback when WebAssembly is not available? Right now the lib just crashes in lib/protocol/crypto.js when loading WASM located in lib/protocol/crypto/poly1305.js…

A few words about my context: installation on iOS (thus no native modules and no WASM) with npm install ssh2 —ignore-scripts —no-optional I manually patched crypto.js to avoid the crash mentioned above, but I also lost the poly1305 functionality…

I believe it would be nicer to have this lib work with a "real" pure javascript implementation (performance is not an issue for me).

Thanks a lot for your help! With my best wishes.

Kind regards, Maurice

mzoliker avatar Jan 03 '24 13:01 mzoliker

const fs = require('fs');

function isWebAssemblySupported() {
  try {
    if (typeof WebAssembly === "object" && typeof WebAssembly.instantiate === "function") {
      const module = new WebAssembly.Module(Uint8Array.of(0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00));
      if (module instanceof WebAssembly.Module) return new WebAssembly.Instance(module) instanceof WebAssembly.Instance;
    }
  } catch (e) {
    console.error("WebAssembly support detection failed:", e);
  }
  return false;
}

let poly1305;
try {
  if (isWebAssemblySupported()) {
    const wasmModule = new WebAssembly.Module(fs.readFileSync('path/to/your/poly1305.wasm'));
    const wasmInstance = new WebAssembly.Instance(wasmModule);
    poly1305 = wasmInstance.exports;
  } else {
    throw new Error("WebAssembly not supported, using JS fallback.");
  }
} catch (error) {
  console.warn("Failed to initialize WebAssembly, using JS fallback:", error);
  poly1305 = require('./poly1305-js'); // Adjust the path to your JS fallback
}

module.exports = poly1305;

ljluestc avatar Jun 24 '24 02:06 ljluestc