feat(web): bring the Senbei workbench to the browser

Add folder scanning, Android library and package recovery, and the localized desktop-style workbench. Keep browser-refused outputs in a fallback ZIP and include logs with folder and ZIP exports.

Align the desktop and web modal transitions and polish the desktop About and legal dialogs.
This commit is contained in:
Momoko-Ayase committed 2026-11-18 17:10:12 +08:00
1 parent 20a68b1c73
commit 21236e8b98
59 files changed
+11612 -3436

No files matched your search

+76
View File
@@ -229,3 +229,79 @@ fn android_samples_restore_against_goldens() {
);
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
/// The byte-level restore the browser binding uses must produce the bytes the
/// path-based driver writes: the same image, the same embedded metadata, and a
/// failure for the same inputs.
#[test]
fn android_samples_restore_identically_in_memory() {
let root = corpus_dir();
if !root.is_dir() {
eprintln!(
"android samples: {} does not exist, nothing to test",
root.display()
);
return;
}
let limits = senbei_engine::android::ResourceLimits::default();
let mut compared = 0usize;
let mut failures: Vec<String> = Vec::new();
for app in app_dirs(&root) {
let mut so_files = Vec::new();
collect_so_files(&app, &mut so_files);
for input in so_files {
let name = input.file_name().unwrap().to_string_lossy().to_string();
let bytes = std::fs::read(&input).expect("read sample");
let on_disk_protected = android::is_protected_so_file(&input);
let (profile, outcome) = android::restore_library_bytes(&bytes, false, &limits);
if !on_disk_protected {
if !matches!(outcome, android::LibraryOutcome::NotProtected) {
failures.push(format!(
"{name}: the file probe says unprotected, the byte probe disagrees"
));
}
continue;
}
let temp = tempfile::tempdir().expect("tempdir");
let dest = temp.path().join("restored.so");
let on_disk = android::restore_so_file(&input, &dest, false);
compared += 1;
match (on_disk, outcome) {
(Ok(embedded), android::LibraryOutcome::Restored(restored)) => {
let written = std::fs::read(&dest).expect("read restored output");
if written != restored.image {
failures.push(format!(
"{name}: in-memory image differs from the written file\n file sha256 {}\n memory sha256 {}",
sha256_hex(&written),
sha256_hex(&restored.image)
));
}
if embedded != restored.embedded_metadata {
failures.push(format!("{name}: embedded metadata differs"));
}
if profile.recovery != senbei_engine::RecoveryStatus::Succeeded {
failures.push(format!("{name}: restored without a recovered profile"));
}
}
(Err(_), android::LibraryOutcome::Failed(_)) => {}
(Ok(_), android::LibraryOutcome::Failed(detail)) => failures.push(format!(
"{name}: the file restore succeeded, the byte restore failed: {}",
detail.text()
)),
(Ok(_), _) => failures.push(format!(
"{name}: the file restore succeeded, the byte probe did not match"
)),
(Err(error), _) => failures.push(format!(
"{name}: the file restore failed ({error:#}), the byte restore did not"
)),
}
}
}
eprintln!(
"android samples: {compared} protected libraries compared, {} difference(s)",
failures.len()
);
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
+309 -187
View File
@@ -1,15 +1,17 @@
//! Native/WASM parity over the same byte API.
//!
//! The browser binding calls `senbei_io::job::unpack_bytes`,
//! `..._force_exe`, `senbei_metadata::deobfuscate`, and
//! The browser binding calls `senbei_io::job::unpack_bytes_profiled`,
//! `..._force_exe_profiled`, `senbei_io::android::restore_library_bytes`,
//! `senbei_io::android::restore_metadata_bytes_profiled`, and
//! `senbei_engine::detect`. This test feeds the *same* fixtures to the native
//! functions and to a `wasm-pack --target nodejs` build of `senbei-wasm`, and
//! compares kind, byte length, SHA-256, remap counts, and suspect state.
//! compares the recovery profile, kind, byte length, SHA-256, remap counts,
//! and suspect state.
//!
//! What this does NOT prove: it uses synthetic, hand-built fixtures only. It
//! says nothing about real protected PE recovery, real Android restoration, or
//! arbitrary third-party binaries — those need fixtures in the corpus and are
//! deliberately out of scope here.
//! What the default run does NOT prove: it uses synthetic, hand-built fixtures
//! only. It says nothing about real protected PE recovery, real Android
//! restoration, or arbitrary third-party binaries. Those are compared only
//! when a private corpus is named (see below).
//!
//! The test is opt-in because it needs a wasm build:
//!
@@ -24,6 +26,8 @@
//! the node binary. Private-corpus parity can be requested by setting
//! `SENBEI_WASM_PARITY_CORPUS=<manifest.json>`: every `pe`/`metadata` case in
//! that harness manifest is also compared, still without writing any output.
//! With `SENBEI_ANDROID_SAMPLES=<dir>` set, every `.so` of every app tree in
//! that directory is restored on both sides and compared as well.
#[path = "support/fixtures.rs"]
mod fixtures;
@@ -131,156 +135,15 @@ fn wasm_parity_is_opt_in_and_reports_why() {
);
}
#[test]
fn synthetic_byte_transforms_match_wasm() {
if !enabled() {
eprintln!("wasm parity skipped (SENBEI_WASM_PARITY not set)");
return;
}
let dir = tempfile::tempdir().unwrap();
let mut jobs = Vec::new();
let mut native = Vec::new();
// Detection: every variant plus a non-target.
for (name, dll, managed) in [
("native-exe.bin", false, false),
("native-dll.bin", true, false),
("managed-exe.bin", false, true),
("managed-dll.bin", true, true),
] {
let bytes = fixtures::synthetic_crackproof_pe(dll, managed);
let path = write_fixture(dir.path(), name, &bytes);
jobs.push(WasmJob {
op: "detect",
input: path,
companion: None,
});
native.push(native_detect(&bytes));
}
let plain = write_fixture(dir.path(), "plain.bin", &fixtures::synthetic_plain_pe());
jobs.push(WasmJob {
op: "detect",
input: plain,
companion: None,
});
native.push(json!({ "ok": true, "kind": null }));
// Metadata: clean (idempotent) and obfuscated (5 rewrites).
let mut metadata_native = Vec::new();
for (name, bytes) in [
("clean.dat", fixtures::clean_metadata()),
("obfuscated.dat", fixtures::obfuscated_metadata()),
] {
let path = write_fixture(dir.path(), name, &bytes);
jobs.push(WasmJob {
op: "metadata",
input: path,
companion: None,
});
let (out, report) = senbei_metadata::deobfuscate(&bytes).unwrap();
metadata_native.push(json!({
"ok": true,
"bytes": out.len(),
"sha256": sha256_hex(&out),
"version": report.version,
"methods": report.methods,
"remapped": report.remapped,
"modules": report.modules,
}));
}
// Metadata probes: both sides must reject with the same error text.
let mut probe_native = Vec::new();
for (name, bytes) in fixtures::malformed_metadata_probes() {
let path = write_fixture(dir.path(), &format!("probe-{name}.dat"), &bytes);
jobs.push(WasmJob {
op: "metadata",
input: path,
companion: None,
});
probe_native.push(match senbei_metadata::deobfuscate(&bytes) {
Ok(_) => json!({ "ok": false, "error": "unexpected success" }),
Err(error) => json!({ "ok": false, "error": error.to_string() }),
});
}
// Native unpack for every detection fixture: both sides must agree on the
// error wording for these non-protected/header-only inputs.
let mut unpack_native = Vec::new();
for (name, dll, managed) in [
("u-native-exe.bin", false, false),
("u-native-dll.bin", true, false),
("u-managed-exe.bin", false, true),
("u-managed-dll.bin", true, true),
] {
let bytes = fixtures::synthetic_crackproof_pe(dll, managed);
let path = write_fixture(dir.path(), name, &bytes);
jobs.push(WasmJob {
op: "unpack",
input: path.clone(),
companion: None,
});
unpack_native.push(match senbei_io::job::unpack_bytes(&bytes, None) {
Ok(image) => json!({
"ok": true,
"kind": kind_name(image.kind),
"bytes": image.bytes.len(),
"sha256": sha256_hex(&image.bytes),
"suspect": !image.integrity.ok(),
"issues": image.integrity.issues,
"companion": image.companion,
}),
Err(error) => json!({ "ok": false, "error": error.to_string() }),
});
// Force-exe is the browser's recovery path; it must agree too.
let path2 = write_fixture(dir.path(), &format!("{name}.force"), &bytes);
jobs.push(WasmJob {
op: "unpack_force_exe",
input: path2,
companion: None,
});
unpack_native.push(match senbei_io::job::unpack_bytes_force_exe(&bytes, None) {
Ok(image) => json!({
"ok": true,
"kind": kind_name(image.kind),
"bytes": image.bytes.len(),
"sha256": sha256_hex(&image.bytes),
"suspect": !image.integrity.ok(),
"issues": image.integrity.issues,
"companion": image.companion,
}),
Err(error) => json!({ "ok": false, "error": error.to_string() }),
});
}
let results = run_wasm(&jobs);
// Negative control: the driver must have produced a real SHA-256 for the
// clean metadata. If the WASM call silently no-op'd, this would not match
// the native digest and the control would fail before the loop below.
let clean_index = jobs
.iter()
.position(|job| job.op == "metadata")
.expect("metadata jobs exist");
let native_clean = &metadata_native[0];
assert_eq!(
results[clean_index]["sha256"], native_clean["sha256"],
"negative control: wasm metadata digest must match native"
);
let all_native: Vec<Value> = native
.into_iter()
.chain(metadata_native)
.chain(probe_native)
.chain(unpack_native)
.collect();
for (index, (want, got)) in all_native.iter().zip(&results).enumerate() {
assert_eq!(
want,
got,
"parity mismatch at job {index} ({}):\nnative {want}\nwasm {got}",
jobs.get(index).map(|job| job.op).unwrap_or("?")
);
}
}
/// The ceilings the browser binding restores under. They must stay the ones
/// in `senbei-wasm/src/lib.rs`, or the two sides stop at different points.
const BROWSER_LIMITS: senbei_engine::android::ResourceLimits =
senbei_engine::android::ResourceLimits {
max_entry_bytes: 1 << 30,
max_total_bytes: 4 << 30,
max_entries: 100_000,
max_depth: 32,
};
fn native_detect(bytes: &[u8]) -> Value {
match senbei_engine::detect(bytes) {
@@ -298,6 +161,217 @@ fn kind_name(kind: senbei_engine::Kind) -> &'static str {
}
}
/// What the binding's `unpack_pe` reports, computed natively.
fn native_unpack(bytes: &[u8], companion: Option<&[u8]>, force_exe: bool) -> Value {
let (profile, result) = if force_exe {
senbei_io::job::unpack_bytes_force_exe_profiled(bytes, companion)
} else {
senbei_io::job::unpack_bytes_profiled(bytes, companion)
};
match result {
Ok(image) => json!({
"ok": true,
"kind": kind_name(image.kind),
"bytes": image.bytes.len(),
"sha256": sha256_hex(&image.bytes),
"suspect": !image.integrity.ok(),
"issues": image.integrity.issues.iter().map(ToString::to_string).collect::<Vec<_>>(),
"companion": image.companion,
"profile": profile,
}),
Err(error) => json!({
"ok": false,
"error": error.message().text(),
"profile": profile,
}),
}
}
/// What the binding's `restore_metadata` reports, computed natively.
fn native_metadata(bytes: &[u8]) -> Value {
use senbei_io::android::{MetadataOutcome, ModuleBinding, restore_metadata_bytes_profiled};
let (profile, outcome) = restore_metadata_bytes_profiled(bytes, ModuleBinding::None);
let reported = |status: &str,
out: Option<&[u8]>,
report: &senbei_metadata::Report,
layout: &senbei_engine::LayoutKind| {
json!({
"ok": true,
"status": status,
"bytes": out.map_or(0, <[u8]>::len),
"sha256": out.map(sha256_hex),
"version": report.version,
"methods": report.methods,
"remapped": report.remapped,
"modules": report.modules,
"layout": layout,
"profile": &profile,
})
};
match &outcome {
MetadataOutcome::Restored {
bytes,
report,
layout,
} => reported("recovered", Some(bytes), report, layout),
MetadataOutcome::Unchanged { report, layout } => {
reported("unchanged", None, report, layout)
}
MetadataOutcome::Unsupported { .. } => json!({
"ok": true,
"status": "unsupported",
"bytes": 0,
"sha256": null,
"version": profile.observed.metadata_version,
"methods": null,
"remapped": null,
"modules": null,
"layout": null,
"profile": &profile,
}),
MetadataOutcome::Failed(error) => json!({
"ok": false,
"error": error.text(),
"profile": &profile,
}),
}
}
/// What the binding's `restore_library` reports, computed natively.
fn native_library(bytes: &[u8]) -> Value {
use senbei_io::android::{LibraryOutcome, restore_library_bytes};
let (profile, outcome) = restore_library_bytes(bytes, false, &BROWSER_LIMITS);
match outcome {
LibraryOutcome::Restored(restored) => json!({
"ok": true,
"status": "recovered",
"bytes": restored.image.len(),
"sha256": sha256_hex(&restored.image),
"embedded": restored.embedded_metadata.as_deref().map(sha256_hex),
"module": restored.method_index_module.as_deref().map(sha256_hex),
"elf": restored.elf,
"profile": profile,
}),
LibraryOutcome::NotProtected => json!({
"ok": true,
"status": "not_protected",
"bytes": 0,
"sha256": null,
"embedded": null,
"module": null,
"elf": null,
"profile": profile,
}),
LibraryOutcome::Failed(error) => json!({
"ok": false,
"error": error.text(),
"profile": profile,
}),
}
}
fn assert_parity(jobs: &[WasmJob], native: &[Value], results: &[Value]) {
assert_eq!(native.len(), results.len(), "one native result per job");
for (index, (want, got)) in native.iter().zip(results).enumerate() {
assert_eq!(
want,
got,
"parity mismatch at job {index} ({} {}):\nnative {want}\nwasm {got}",
jobs[index].op,
jobs[index].input.display()
);
}
}
#[test]
fn synthetic_byte_transforms_match_wasm() {
if !enabled() {
eprintln!("wasm parity skipped (SENBEI_WASM_PARITY not set)");
return;
}
let dir = tempfile::tempdir().unwrap();
let mut jobs = Vec::new();
let mut native = Vec::new();
let mut job = |op: &'static str, name: &str, bytes: &[u8]| {
jobs.push(WasmJob {
op,
input: write_fixture(dir.path(), name, bytes),
companion: None,
});
};
let variants = [
("native-exe.bin", false, false),
("native-dll.bin", true, false),
("managed-exe.bin", false, true),
("managed-dll.bin", true, true),
];
// Detection: every variant plus a non-target.
for (name, dll, managed) in variants {
let bytes = fixtures::synthetic_crackproof_pe(dll, managed);
job("detect", name, &bytes);
native.push(native_detect(&bytes));
}
let plain = fixtures::synthetic_plain_pe();
job("detect", "plain.bin", &plain);
native.push(json!({ "ok": true, "kind": null }));
// Metadata: clean (validated, nothing to rewrite) and obfuscated (5
// rewrites), then blobs both sides must refuse in the same words.
let metadata_start = native.len();
for (name, bytes) in [
("clean.dat", fixtures::clean_metadata()),
("obfuscated.dat", fixtures::obfuscated_metadata()),
] {
job("metadata", name, &bytes);
native.push(native_metadata(&bytes));
}
for (name, bytes) in fixtures::malformed_metadata_probes() {
job("metadata", &format!("probe-{name}.dat"), &bytes);
native.push(native_metadata(&bytes));
}
// Unpack for every detection fixture, by both routes: the two sides must
// agree on the profile and the error wording for these header-only inputs.
// The EXE-only route is the page's retry after a trap.
for (name, dll, managed) in variants {
let bytes = fixtures::synthetic_crackproof_pe(dll, managed);
job("unpack", &format!("u-{name}"), &bytes);
native.push(native_unpack(&bytes, None, false));
job("unpack_force_exe", &format!("f-{name}"), &bytes);
native.push(native_unpack(&bytes, None, true));
}
// Library: inputs that are not protected AArch64 libraries.
for (name, bytes) in [
("plain.so", plain.clone()),
("stub.so", b"\x7fELF\x02\x01\x01".to_vec()),
("empty.so", Vec::new()),
] {
job("library", name, &bytes);
native.push(native_library(&bytes));
}
let results = run_wasm(&jobs);
// Negative control: the driver must have rewritten the obfuscated blob and
// hashed real bytes. If the WASM call silently did nothing, the status and
// digest would not be these.
assert_eq!(
results[metadata_start]["status"], "unchanged",
"clean metadata needs no rewrite"
);
let rewritten = &results[metadata_start + 1];
assert_eq!(rewritten["status"], "recovered", "{rewritten}");
assert_eq!(rewritten["remapped"], 5, "{rewritten}");
assert!(rewritten["sha256"].is_string());
assert_eq!(
rewritten["sha256"],
native[metadata_start + 1]["sha256"],
"negative control: wasm metadata digest must match native"
);
assert_parity(&jobs, &native, &results);
}
/// Optional: compare private corpus cases as well, when a harness manifest and
/// the gate are both provided. Restored bytes still go nowhere.
#[test]
@@ -327,45 +401,21 @@ fn optional_private_corpus_parity() {
let comp = companion
.as_ref()
.map(|path| std::fs::read(path).expect("read companion"));
native.push(native_unpack(&bytes, comp.as_deref(), false));
jobs.push(WasmJob {
op: "unpack",
input: input.clone(),
companion: companion.clone(),
input,
companion,
});
native.push(
match senbei_io::job::unpack_bytes(&bytes, comp.as_deref()) {
Ok(image) => json!({
"ok": true,
"kind": kind_name(image.kind),
"bytes": image.bytes.len(),
"sha256": sha256_hex(&image.bytes),
"suspect": !image.integrity.ok(),
"issues": image.integrity.issues,
"companion": image.companion,
}),
Err(error) => json!({ "ok": false, "error": error.to_string() }),
},
);
}
"metadata" => {
let bytes = std::fs::read(&input).expect("read corpus metadata");
native.push(native_metadata(&bytes));
jobs.push(WasmJob {
op: "metadata",
input,
companion: None,
});
native.push(match senbei_metadata::deobfuscate(&bytes) {
Ok((out, detail)) => json!({
"ok": true,
"bytes": out.len(),
"sha256": sha256_hex(&out),
"version": detail.version,
"methods": detail.methods,
"remapped": detail.remapped,
"modules": detail.modules,
}),
Err(error) => json!({ "ok": false, "error": error.to_string() }),
});
}
_ => {}
}
@@ -375,11 +425,83 @@ fn optional_private_corpus_parity() {
return;
}
let results = run_wasm(&jobs);
for (want, got) in native.iter().zip(&results) {
assert_eq!(want, got, "private corpus parity mismatch");
assert_parity(&jobs, &native, &results);
}
/// Every `.so` below `dir`, skipping previous output trees.
fn collect_libraries(dir: &Path, out: &mut Vec<PathBuf>) {
let mut entries: Vec<PathBuf> = std::fs::read_dir(dir)
.unwrap_or_else(|error| panic!("read {}: {error}", dir.display()))
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
.collect();
entries.sort();
for path in entries {
if path.is_dir() {
if path
.file_name()
.is_some_and(|name| !name.eq_ignore_ascii_case("unpack"))
{
collect_libraries(&path, out);
}
} else if path
.extension()
.is_some_and(|extension| extension.eq_ignore_ascii_case("so"))
{
out.push(path);
}
}
}
/// Optional: restore every library of the private Android corpus on both
/// sides. Each app tree is an immediate subdirectory with a `lib/` folder.
#[test]
fn optional_android_corpus_parity() {
if !enabled() {
return;
}
let Some(root) = std::env::var_os("SENBEI_ANDROID_SAMPLES").map(PathBuf::from) else {
return;
};
let mut apps: Vec<PathBuf> = std::fs::read_dir(&root)
.unwrap_or_else(|error| panic!("read {}: {error}", root.display()))
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
.filter(|path| path.join("lib").is_dir())
.collect();
apps.sort();
let mut libraries = Vec::new();
for app in apps {
collect_libraries(&app.join("lib"), &mut libraries);
}
if libraries.is_empty() {
eprintln!(
"android corpus parity: no libraries under {}",
root.display()
);
return;
}
let mut jobs = Vec::new();
let mut native = Vec::new();
for input in libraries {
let bytes = std::fs::read(&input).expect("read corpus library");
native.push(native_library(&bytes));
jobs.push(WasmJob {
op: "library",
input,
companion: None,
});
}
let restored = native
.iter()
.filter(|result| result["status"] == "recovered")
.count();
eprintln!(
"android corpus parity: {} libraries, {restored} restored natively",
jobs.len()
);
let results = run_wasm(&jobs);
assert_parity(&jobs, &native, &results);
}
/// Minimal in-process harness invocation shared with the example's module.
fn harness_run(manifest: &Path) -> Value {
#[path = "support/harness.rs"]
+100 -39
View File
@@ -1,14 +1,18 @@
// Native/WASM parity driver. Reads a JSON job list on stdin and prints one
// JSON result per job on stdout. The Rust test starts `node` with this file.
//
// Job: { "op": "detect" | "unpack" | "unpack_force_exe" | "metadata",
// Job: { "op": "detect" | "unpack" | "unpack_force_exe" | "metadata" | "library",
// "input": "<path>", "companion": "<path>|null" }
// Result: { "ok": true, "kind": ..., "bytes": <n>, "sha256": ...,
// "suspect": ..., "issues": [...], "remapped": ... }
// or { "ok": false, "error": "..." }
// Result: { "ok": true, ... } with the fields of the job's kind (see `runJob`),
// or { "ok": false, "error": "...", "profile": {...} }
//
// The wasm package directory is argv[2] (wasm-pack --target nodejs output).
//
// The driver calls the binding the way `web/worker.js` does: the input is
// appended to an `InputBuffer` in slices, the recovered bytes are read through
// the views the outcome hands out, and the digests the binding computes are
// checked against digests of those bytes.
//
// Isolation: every job runs in a *fresh Node Worker thread* and that worker is
// terminated before the next job starts. This matches the browser binding's
// disposable-worker architecture: WebAssembly cannot recover from a trap in the
@@ -21,7 +25,7 @@
// hung call; on expiry the worker is terminated and the job reports an error.
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { closeSync, fstatSync, openSync, readFileSync, readSync } from "node:fs";
import { createInterface } from "node:readline";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
@@ -32,55 +36,112 @@ function sha256(bytes) {
return createHash("sha256").update(bytes).digest("hex");
}
const SLICE = 8 * 1024 * 1024;
// Fill an `InputBuffer` from a file in slices, as the page does from a Blob.
function load(wasm, file) {
const fd = openSync(file, "r");
try {
const size = fstatSync(fd).size;
const buffer = new wasm.InputBuffer(size);
const slice = Buffer.allocUnsafe(Math.min(SLICE, Math.max(size, 1)));
for (;;) {
const read = readSync(fd, slice, 0, slice.length, null);
if (read === 0) break;
buffer.append(slice.subarray(0, read));
}
if (buffer.length !== size) throw new Error("short read");
return buffer;
} finally {
closeSync(fd);
}
}
// The digest of a view, which must agree with the digest the binding reports.
// The view is hashed first: it is valid only until the next call into the
// module, and `report` is such a call.
function digestOf(view, report) {
if (!view || view.length === 0) return null;
const digest = sha256(view);
const reported = report();
if (reported !== digest) throw new Error(`binding digest ${reported} is not the bytes' ${digest}`);
return digest;
}
// Runs in a worker: one job, one freshly instantiated module.
function runJob(pkgDir, job) {
const require = createRequire(import.meta.url);
const wasm = require(path.join(pkgDir, "senbei_wasm.js"));
let handle;
if (job.op === "detect") {
return { ok: true, kind: wasm.detect(readFileSync(job.input)) ?? null };
}
const input = load(wasm, job.input);
let outcome;
try {
if (job.op === "detect") {
const bytes = readFileSync(job.input);
return { ok: true, kind: wasm.detect(bytes) ?? null };
}
if (job.op === "unpack" || job.op === "unpack_force_exe") {
const input = readFileSync(job.input);
const companion = job.companion ? readFileSync(job.companion) : undefined;
handle =
job.op === "unpack"
? wasm.unpack_file(input, companion)
: wasm.unpack_file_force_exe(input, companion);
const bytes = handle.bytes;
return {
ok: true,
kind: handle.kind,
bytes: bytes.length,
sha256: sha256(bytes),
suspect: handle.suspect,
issues: handle.issues,
companion: handle.companion,
};
// `unpack_pe` takes the companion buffer over.
const companion = job.companion ? load(wasm, job.companion) : undefined;
outcome = wasm.unpack_pe(input, companion, job.op === "unpack_force_exe", "en", undefined);
} else if (job.op === "metadata") {
outcome = wasm.restore_metadata(input, undefined, 0, "en");
} else if (job.op === "library") {
outcome = wasm.restore_library(input, "en", undefined);
} else {
return { ok: false, error: `unknown op ${job.op}` };
}
const info = JSON.parse(outcome.info);
const profile = info.profile;
if (info.status === "failed") return { ok: false, error: info.error?.text ?? null, profile };
// Each view is used before the next call into the module.
const image = outcome.image();
const bytes = image.length;
const digest = digestOf(image, () => outcome.image_sha256());
if (job.op === "metadata") {
const data = readFileSync(job.input);
handle = wasm.deobfuscate_metadata(data);
const bytes = handle.bytes;
return {
ok: true,
bytes: bytes.length,
sha256: sha256(bytes),
version: handle.version,
methods: handle.methods,
remapped: handle.remapped,
modules: handle.modules,
status: info.status,
bytes,
sha256: digest,
version: info.metadata?.version ?? null,
methods: info.metadata?.methods ?? null,
remapped: info.metadata?.remapped ?? null,
modules: info.metadata?.modules ?? null,
layout: info.metadata?.layout ?? null,
profile,
};
}
return { ok: false, error: `unknown op ${job.op}` };
if (job.op === "library") {
const embedded = digestOf(outcome.embedded_metadata(), () => outcome.embedded_metadata_sha256());
const module = outcome.take_module();
return {
ok: true,
status: info.status,
bytes,
sha256: digest,
embedded,
module: module ? sha256(module) : null,
elf: info.elf,
profile,
};
}
return {
ok: true,
kind: info.kind,
bytes,
sha256: digest,
suspect: info.suspect,
issues: info.findings.map((finding) => finding.message),
companion: info.companion,
profile,
};
} finally {
// The worker is terminated immediately after this, so this is belt and
// braces: release the Rust-side allocation without waiting for GC.
if (handle && typeof handle.free === "function") {
// braces: release the Rust-side allocations without waiting for GC.
for (const handle of [outcome, input]) {
try {
handle.free();
handle?.free();
} catch {
// A poisoned instance after a trap can refuse; the worker dies anyway.
}