securityos/node_modules/wasi-js/dist/runtime.js

75 lines
2.6 KiB
JavaScript
Raw Permalink Normal View History

2024-09-06 15:32:35 +00:00
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.run = void 0;
const wasi_1 = __importDefault(require("./wasi"));
const node_1 = __importDefault(require("./bindings/node"));
const fs_1 = __importDefault(require("fs"));
const promises_1 = require("fs/promises");
const debug_1 = __importDefault(require("debug"));
const log = (0, debug_1.default)("wasi");
async function wasmImport(name, options = {}) {
const pathToWasm = `${name}${name.endsWith(".wasm") ? "" : ".wasm"}`;
function getrandom(bufPtr, bufLen, _flags) {
// NOTE: returning 0 here (our default stub behavior)
// would result in Python hanging on startup! So critical to do this.
node_1.default.randomFillSync(
// @ts-ignore
new Uint8Array(result.instance.exports.memory.buffer), bufPtr, bufLen);
return bufLen;
}
const wasmOpts = {
env: new Proxy({ getrandom, ...options?.env }, {
get(target, key) {
if (key in target) {
return Reflect.get(target, key);
}
log("WARNING: creating stub for", key);
return (..._args) => {
return 0;
};
},
}),
};
let wasi = undefined;
if (!options?.noWasi) {
const opts = {
args: process.argv,
bindings: node_1.default,
env: process.env,
};
if (options.dir === null) {
// sandbox -- don't give any fs access
}
else {
opts.bindings = {
...node_1.default,
fs: fs_1.default,
};
// just give full access; security of fs access isn't
// really relevant for us at this point
if (!options.dir) {
opts.preopens = { "/": "/" };
}
else {
opts.preopens = { [options.dir]: options.dir };
}
}
wasi = new wasi_1.default(opts);
wasmOpts.wasi_snapshot_preview1 = wasi.wasiImport;
}
//console.log(`reading ${pathToWasm}`);
const source = await (0, promises_1.readFile)(pathToWasm);
const typedArray = new Uint8Array(source);
const result = await WebAssembly.instantiate(typedArray, wasmOpts);
if (wasi != null) {
wasi.start(result.instance);
}
}
async function run(name, options = {}) {
await wasmImport(name, options);
}
exports.run = run;
//# sourceMappingURL=runtime.js.map