mscdex / ssh2

SSH2 client and server modules written in pure JavaScript for node.js
MIT License
5.52k stars 665 forks source link

Pure JS fallback when WASM is not available #1356

Open mzoliker opened 10 months ago

mzoliker commented 10 months ago

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

ljluestc commented 4 months ago
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;