diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 04c5735..95c4d22 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -94,6 +94,7 @@ jobs: - uses: actions/setup-node@v4 with: node-version: '24' + - run: npm test --prefix web - run: cargo install wasm-pack --locked # `-- --locked` forwards to cargo: senbei-wasm/Cargo.lock is committed on # purpose, so the wasm build must be pinned by it rather than silently @@ -114,6 +115,7 @@ jobs: path: | web/index.html web/app.js + web/report.js web/worker.js web/style.css web/pkg/ diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1097440..726d956 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -71,7 +71,7 @@ jobs: - name: Stage static site run: | mkdir dist - cp web/index.html web/app.js web/worker.js web/style.css dist/ + cp web/index.html web/app.js web/report.js web/worker.js web/style.css dist/ cp -r web/pkg dist/pkg - uses: cloudflare/wrangler-action@v3 with: diff --git a/senbei-wasm/Cargo.lock b/senbei-wasm/Cargo.lock index 2acc7da..cdc6f3b 100644 --- a/senbei-wasm/Cargo.lock +++ b/senbei-wasm/Cargo.lock @@ -507,6 +507,7 @@ dependencies = [ "senbei-engine", "senbei-io", "senbei-metadata", + "serde_json", "wasm-bindgen", ] diff --git a/senbei-wasm/Cargo.toml b/senbei-wasm/Cargo.toml index 9548234..168b1bf 100644 --- a/senbei-wasm/Cargo.toml +++ b/senbei-wasm/Cargo.toml @@ -13,6 +13,7 @@ crate-type = ["cdylib"] senbei-io = { path = "../senbei-io" } senbei-metadata = { path = "../senbei-metadata" } senbei-engine = { path = "../senbei-engine" } +serde_json = "1" wasm-bindgen = "0.2" console_error_panic_hook = "0.1" diff --git a/senbei-wasm/src/lib.rs b/senbei-wasm/src/lib.rs index 888c915..3579ea1 100644 --- a/senbei-wasm/src/lib.rs +++ b/senbei-wasm/src/lib.rs @@ -3,6 +3,7 @@ //! Everything here is I/O-free: the browser hands in file bytes and gets //! unpacked file bytes back. No network, no filesystem, no uploads. +use senbei_engine::{IntegrityReport, IntegritySeverity, ProtectionProfile, UnpackError}; use wasm_bindgen::prelude::*; /// Install a panic hook that forwards Rust panic messages to the browser @@ -12,6 +13,23 @@ pub fn init_panic_hook() { console_error_panic_hook::set_once(); } +/// Serialize a profile for the JS layer. +/// +/// `ProtectionProfile` has a derived serializer and no fallible field, but a +/// serialization failure must never panic inside wasm, so the fallback is the +/// JSON literal `null`. +fn profile_json(profile: &ProtectionProfile) -> String { + serde_json::to_string(profile).unwrap_or_else(|_| "null".to_string()) +} + +/// `"fatal"` / `"warning"`, matching the labels the JSON report uses. +fn severity_label(severity: IntegritySeverity) -> &'static str { + match severity { + IntegritySeverity::Fatal => "fatal", + IntegritySeverity::Warning => "warning", + } +} + /// Result of unpacking one protected module. #[wasm_bindgen] pub struct UnpackResult { @@ -20,6 +38,9 @@ pub struct UnpackResult { suspect: bool, issues: Vec, companion: bool, + severities: Vec, + fatal: bool, + profile_json: Option, } #[wasm_bindgen] @@ -56,6 +77,29 @@ impl UnpackResult { pub fn companion(&self) -> bool { self.companion } + + /// Severity of each entry in [`Self::issues`] at the same index: + /// `"fatal"` or `"warning"`. A fatal finding means the loader or CLR + /// rejects the image; a warning means a recoverable region looks + /// unrestored. + #[wasm_bindgen(getter)] + pub fn severities(&self) -> Vec { + self.severities.clone() + } + + /// True when at least one finding is fatal. + #[wasm_bindgen(getter)] + pub fn fatal(&self) -> bool { + self.fatal + } + + /// The recovery profile as JSON, or `undefined` when the call did not + /// collect one. See [`unpack_file_reported`] for the variant that always + /// carries the profile, including on failure. + #[wasm_bindgen(getter)] + pub fn profile_json(&self) -> Option { + self.profile_json.clone() + } } /// Result of de-obfuscating an il2cpp `global-metadata.dat`. @@ -110,6 +154,28 @@ fn kind_str(kind: senbei_engine::Kind) -> &'static str { } } +/// Copy an integrity report's findings into the parallel arrays the JS layer +/// reads (`issues[i]` and `severities[i]` describe the same defect). +fn split_findings(report: &IntegrityReport) -> (Vec, Vec, bool) { + let issues = report.issues.clone(); + let mut severities = Vec::with_capacity(report.findings.len()); + let mut fatal = false; + for finding in &report.findings { + let label = severity_label(finding.severity); + if finding.severity == IntegritySeverity::Fatal { + fatal = true; + } + severities.push(label.to_string()); + } + // `issues` and `findings` are documented to have the same order and + // length; if a future change breaks that, the UI must still line up. + if severities.len() != issues.len() { + severities = issues.iter().map(|_| "warning".to_string()).collect(); + fatal = false; + } + (issues, severities, fatal) +} + /// Classify a file's bytes without unpacking. /// /// Returns `"native-exe"`, `"managed-exe"`, `"native-dll"`, `"managed-dll"`, @@ -123,6 +189,35 @@ pub fn detect(input: &[u8]) -> Option { senbei_engine::detect(input).map(|d| kind_str(d.kind).to_string()) } +/// Return the pre-recovery profile for an input as JSON. +/// +/// This never runs a recovery, so every candidate stays `not_attempted` and +/// `selected` is `null`. Two things are deliberately kept separate in the +/// returned document: +/// +/// * a PE input reports `recognition: "recognized"` only when the header key +/// table carries the supported magic; +/// * an il2cpp metadata input reports the observed format version with +/// `recognition: "not_attempted"`, because a metadata magic/version match +/// identifies a format, not a protection. +/// +/// Always returns a JSON object (never `null`); an unrecognized input gets a +/// profile with `recognition: "not_recognized"`. +#[wasm_bindgen] +pub fn inspect_profile_json(input: &[u8]) -> String { + if let Some(identity) = senbei_metadata::identify(input) { + let version = identity.version.raw(); + let mut profile = + ProtectionProfile::new(senbei_engine::ObservedTarget::metadata(Some(version))); + profile.push_warning( + "the il2cpp metadata magic and version identify a file format; \ + they do not establish that the file is protected", + ); + return profile_json(&profile); + } + profile_json(&senbei_engine::inspect_profile(input)) +} + /// Unpack a protected module. /// /// `input` is the protected `.exe`/`.dll`; `companion` is the optional @@ -133,13 +228,7 @@ pub fn detect(input: &[u8]) -> Option { pub fn unpack_file(input: &[u8], companion: Option>) -> Result { let r = senbei_io::job::unpack_bytes(input, companion.as_deref()) .map_err(|e| JsError::new(&e.to_string()))?; - Ok(UnpackResult { - kind: kind_str(r.kind).to_string(), - bytes: r.bytes, - suspect: !r.integrity.ok(), - issues: r.integrity.issues, - companion: r.companion, - }) + Ok(UnpackResult::from_image(r)) } /// De-obfuscate the method tokens of an il2cpp `global-metadata.dat`. @@ -160,6 +249,191 @@ pub fn deobfuscate_metadata(data: &[u8]) -> Result { }) } +/// De-obfuscate metadata and return the transform profile alongside it. +/// +/// [`deobfuscate_metadata`] throws; this variant never does, so the web worker +/// can report why an input was rejected and still export a profile for it. +/// +/// The profile records `ValidatedMetadataTransform` evidence only after the +/// transform actually rewrote tokens. A metadata that is already clean is +/// reported as `recognition: "not_recognized"` with a warning: its header +/// identifies the format, not a protection. +#[wasm_bindgen] +pub fn deobfuscate_metadata_reported(data: &[u8]) -> MetadataReport { + let (version, profile, result) = metadata_outcome(data); + MetadataReport::from_outcome(version, profile, result) +} + +/// Build the metadata profile the same way the I/O report does, so the browser +/// export and the CLI JSON report describe one transform identically. +/// +/// * a successful rewrite is the only case that claims +/// `ValidatedMetadataTransform` evidence; +/// * an already-clean blob is `not_recognized` — the header matched, but +/// nothing was transformed, so there is no protection evidence; +/// * the PE static check does not apply to metadata output, so +/// `static_validation` stays `not_run` in every case. +fn metadata_outcome( + data: &[u8], +) -> ( + Option, + ProtectionProfile, + Result<(Vec, senbei_metadata::Report), senbei_metadata::Error>, +) { + use senbei_engine::{ + AttemptOutcome, LayoutAttempt, LayoutKind, ObservedTarget, ProtectionEvidence, + RecognitionStatus, RecoveryStatus, ValidationStatus, + }; + + let identity = senbei_metadata::identify(data); + let version = identity.map(|identity| identity.raw_version); + let mut profile = ProtectionProfile::new(ObservedTarget::metadata(version)); + if identity.is_none() { + profile.recognition = RecognitionStatus::NotRecognized; + profile.push_error("not an il2cpp global-metadata.dat"); + return (version, profile, Err(senbei_metadata::Error::NotMetadata)); + } + // The structural transform is the route this binding runs. A version that + // identifies but has no structural layout still gets this candidate, and + // the transform's own error explains the refusal. + let route = LayoutKind::MetadataStructural; + let result = senbei_metadata::deobfuscate(data); + match &result { + Ok((_, report)) if report.remapped > 0 => { + profile.recognition = RecognitionStatus::Recognized; + profile.evidence = vec![ProtectionEvidence::ValidatedMetadataTransform]; + profile.candidates = vec![LayoutAttempt { + layout: route, + outcome: AttemptOutcome::Succeeded, + warnings: Vec::new(), + errors: Vec::new(), + }]; + profile.selected = Some(route); + profile.recovery = RecoveryStatus::Succeeded; + } + Ok(_) => { + profile.recognition = RecognitionStatus::NotRecognized; + profile.candidates = vec![LayoutAttempt { + layout: route, + outcome: AttemptOutcome::Succeeded, + warnings: Vec::new(), + errors: Vec::new(), + }]; + profile.push_warning("metadata is already de-obfuscated; no tokens were rewritten"); + } + Err(error) => { + profile.recognition = RecognitionStatus::Recognized; + profile.candidates = vec![LayoutAttempt { + layout: route, + outcome: AttemptOutcome::Failed, + warnings: Vec::new(), + errors: vec![error.to_string()], + }]; + profile.recovery = RecoveryStatus::Failed; + profile.push_error(error.to_string()); + } + } + profile.static_validation = ValidationStatus::NotRun; + (version, profile, result) +} + +/// Outcome of [`deobfuscate_metadata_reported`]. +#[wasm_bindgen] +pub struct MetadataReport { + ok: bool, + bytes: Vec, + version: u32, + methods: usize, + remapped: usize, + modules: usize, + error: Option, + profile_json: String, +} + +#[wasm_bindgen] +impl MetadataReport { + /// True when the transform succeeded. A successful run may still have + /// rewritten nothing — check [`Self::remapped`]. + #[wasm_bindgen(getter)] + pub fn ok(&self) -> bool { + self.ok + } + + /// The (possibly rewritten) metadata bytes; empty when [`Self::ok`] is false. + #[wasm_bindgen(getter)] + pub fn bytes(&self) -> Vec { + self.bytes.clone() + } + + /// Raw header version, or 0 when the input was not metadata. + #[wasm_bindgen(getter)] + pub fn version(&self) -> u32 { + self.version + } + + /// Total method-definition entries (0 on failure). + #[wasm_bindgen(getter)] + pub fn methods(&self) -> usize { + self.methods + } + + /// Method tokens actually rewritten. + #[wasm_bindgen(getter)] + pub fn remapped(&self) -> usize { + self.remapped + } + + /// Modules (images) owning at least one method. + #[wasm_bindgen(getter)] + pub fn modules(&self) -> usize { + self.modules + } + + /// The error message when [`Self::ok`] is false. + #[wasm_bindgen(getter)] + pub fn error(&self) -> Option { + self.error.clone() + } + + /// The transform profile as JSON, in every case. + #[wasm_bindgen(getter)] + pub fn profile_json(&self) -> String { + self.profile_json.clone() + } +} + +impl MetadataReport { + fn from_outcome( + version: Option, + profile: ProtectionProfile, + result: Result<(Vec, senbei_metadata::Report), senbei_metadata::Error>, + ) -> Self { + let profile_json = profile_json(&profile); + match result { + Ok((bytes, report)) => Self { + ok: true, + bytes, + version: report.version, + methods: report.methods, + remapped: report.remapped, + modules: report.modules, + error: None, + profile_json, + }, + Err(error) => Self { + ok: false, + bytes: Vec::new(), + version: version.unwrap_or(0), + methods: 0, + remapped: 0, + modules: 0, + error: Some(error.to_string()), + profile_json, + }, + } + } +} + /// Unpack a protected module, forcing the EXE pipeline (no DLL-pipeline /// probe). See [`senbei_io::job::unpack_bytes_force_exe`] for why the web app /// needs this recovery path. @@ -170,11 +444,167 @@ pub fn unpack_file_force_exe( ) -> Result { let r = senbei_io::job::unpack_bytes_force_exe(input, companion.as_deref()) .map_err(|e| JsError::new(&e.to_string()))?; - Ok(UnpackResult { - kind: kind_str(r.kind).to_string(), - bytes: r.bytes, - suspect: !r.integrity.ok(), - issues: r.integrity.issues, - companion: r.companion, - }) + Ok(UnpackResult::from_image(r)) +} + +impl UnpackResult { + fn from_image(r: senbei_io::job::UnpackedImage) -> Self { + let (issues, severities, fatal) = split_findings(&r.integrity); + Self { + kind: kind_str(r.kind).to_string(), + bytes: r.bytes, + suspect: !r.integrity.ok(), + issues, + companion: r.companion, + severities, + fatal, + profile_json: None, + } + } +} + +/// Outcome of [`unpack_file_reported`]: success data or the error message, +/// plus the recovery profile in both cases. +/// +/// Unlike [`UnpackResult`], this never throws for an unpack failure. The web +/// worker needs the failed routes (which pipeline ran, why it was rejected) to +/// show why a file did not recover; a thrown string would lose them. +#[wasm_bindgen] +pub struct UnpackReport { + ok: bool, + kind: String, + bytes: Vec, + suspect: bool, + issues: Vec, + severities: Vec, + fatal: bool, + companion: bool, + error: Option, + profile_json: String, +} + +#[wasm_bindgen] +impl UnpackReport { + /// True when recovery produced an image. + #[wasm_bindgen(getter)] + pub fn ok(&self) -> bool { + self.ok + } + + /// Detected module kind (same labels as [`UnpackResult::kind`]); empty when + /// the input was not recognized as a supported target. + #[wasm_bindgen(getter)] + pub fn kind(&self) -> String { + self.kind.clone() + } + + /// The unpacked image bytes (empty when [`Self::ok`] is false). + #[wasm_bindgen(getter)] + pub fn bytes(&self) -> Vec { + self.bytes.clone() + } + + /// True when the static integrity check flagged the image as likely broken. + #[wasm_bindgen(getter)] + pub fn suspect(&self) -> bool { + self.suspect + } + + /// Integrity defects, in the checker's order. + #[wasm_bindgen(getter)] + pub fn issues(&self) -> Vec { + self.issues.clone() + } + + /// Severity of each [`Self::issues`] entry: `"fatal"` or `"warning"`. + #[wasm_bindgen(getter)] + pub fn severities(&self) -> Vec { + self.severities.clone() + } + + /// True when at least one finding is fatal. + #[wasm_bindgen(getter)] + pub fn fatal(&self) -> bool { + self.fatal + } + + /// True when the input was reconstructed from an external `._` companion. + #[wasm_bindgen(getter)] + pub fn companion(&self) -> bool { + self.companion + } + + /// The error message when [`Self::ok`] is false. + #[wasm_bindgen(getter)] + pub fn error(&self) -> Option { + self.error.clone() + } + + /// The recovery profile as JSON, in every case — including failures and + /// inputs that were never recognized. + #[wasm_bindgen(getter)] + pub fn profile_json(&self) -> String { + self.profile_json.clone() + } +} + +/// Unpack with the full profile, without throwing on an unpack failure. +/// +/// `force_exe` selects the EXE-only route (the web app's retry path for a DLL +/// whose DLL-first probe trapped). See [`unpack_file`] for the arguments. +#[wasm_bindgen] +pub fn unpack_file_reported( + input: &[u8], + companion: Option>, + force_exe: bool, +) -> UnpackReport { + let (profile, result) = if force_exe { + senbei_io::job::unpack_bytes_force_exe_profiled(input, companion.as_deref()) + } else { + senbei_io::job::unpack_bytes_profiled(input, companion.as_deref()) + }; + UnpackReport::from_outcome(profile, result) +} + +impl UnpackReport { + fn from_outcome( + profile: ProtectionProfile, + result: Result, + ) -> Self { + let profile_json = profile_json(&profile); + let kind = profile + .observed + .kind + .map(|kind| kind_str(kind).to_string()) + .unwrap_or_default(); + match result { + Ok(r) => { + let (issues, severities, fatal) = split_findings(&r.integrity); + Self { + ok: true, + kind: kind_str(r.kind).to_string(), + bytes: r.bytes, + suspect: !r.integrity.ok(), + issues, + severities, + fatal, + companion: r.companion, + error: None, + profile_json, + } + } + Err(error) => Self { + ok: false, + kind, + bytes: Vec::new(), + suspect: false, + issues: Vec::new(), + severities: Vec::new(), + fatal: false, + companion: profile.observed.external_companion, + error: Some(error.to_string()), + profile_json, + }, + } + } } diff --git a/web/app.js b/web/app.js index d7d2341..8013c32 100644 --- a/web/app.js +++ b/web/app.js @@ -1,4 +1,18 @@ -import init, { detect, deobfuscate_metadata } from './pkg/senbei_wasm.js'; +import init, { detect, inspect_profile_json } from './pkg/senbei_wasm.js'; +import { + DEFAULT_INPUT_LIMIT_BYTES, + MAX_INPUT_LIMIT_MIB, + MIN_INPUT_LIMIT_MIB, + buildReport, + describeFindings, + describeObserved, + describeStages, + formatBytes, + parseLimitMiB, + planReadBudget, + reportFileName, + serializeReport, +} from './report.js'; const dropzone = document.getElementById('dropzone'); const picker = document.getElementById('picker'); @@ -6,6 +20,9 @@ const fileList = document.getElementById('files'); const actions = document.getElementById('actions'); const unpackBtn = document.getElementById('unpack-btn'); const clearBtn = document.getElementById('clear-btn'); +const exportBtn = document.getElementById('export-btn'); +const limitInput = document.getElementById('limit-mib'); +const limitHint = document.getElementById('limit-hint'); const legalOverlay = document.getElementById('legal-overlay'); const legalAccept = document.getElementById('legal-accept'); const legalLink = document.getElementById('legal-link'); @@ -34,10 +51,16 @@ legalLink.addEventListener('click', (e) => { /** name -> { * file: File, * kind: string|undefined, // detect() result; undefined for `._` files - * state: 'staged'|'working'|'ok'|'err', + * state: 'staged'|'working'|'ok'|'err'|'blocked', * bytes: Uint8Array|null, // unpacked output (state 'ok') * note: string, // status line (kind, suspect issues, error) * suspect: boolean, + * findings: Array<{severity,message}>, // integrity defects + * profile: object|null, // post-recovery profile (or the failure profile) + * preRecoveryProfile: object|null, // inspect_profile_json() result + * retried: boolean, // forced-EXE retry ran + * companionUsed: boolean, // output was spliced from a `._` payload + * error: string|null, * } */ const files = new Map(); @@ -96,6 +119,52 @@ dropzone.addEventListener('drop', (e) => { stageFiles(e.dataTransfer.files); }); +// --- Input budget --------------------------------------------------------- +// +// Every read is guarded from `File.size` BEFORE `arrayBuffer()` runs, so an +// oversized input never becomes a large allocation in the first place. The +// limit is a practical guard, not a memory measurement: see the warning text. + +let limitBytes = DEFAULT_INPUT_LIMIT_BYTES; + +limitInput.min = String(MIN_INPUT_LIMIT_MIB); +limitInput.max = String(MAX_INPUT_LIMIT_MIB); + +/** Static explanation shown when no staged input needs attention. */ +const LIMIT_BASE_HINT = + `Modules above the limit are skipped before their bytes are read. ` + + 'Unpacking keeps the input, the recovered image, and pipeline buffers in ' + + 'memory together, so it needs several times the file size.'; + +function applyLimit() { + limitBytes = parseLimitMiB(limitInput.value, limitBytes); + render(); +} + +limitInput.addEventListener('change', () => { + limitInput.value = String(Math.round(limitBytes / (1024 * 1024))); + applyLimit(); +}); +limitInput.addEventListener('input', () => { + // Only react to a value that is actually usable, so typing never flips the + // budget on a partial number. + if (parseLimitMiB(limitInput.value, null) !== null) applyLimit(); +}); + +/** Latest budget plan for the staged set (recomputed by render()). */ +let budgetPlan = null; + +/** Entries measured for the budget: base module + its `._` companion. */ +function stagedSizes() { + return [...files].map(([name, entry]) => ({ name, size: entry.file.size })); +} + +/** True when `name` must be skipped under the current budget. */ +function isBlocked(name) { + if (!budgetPlan) return false; + return budgetPlan.blocked.includes(name); +} + async function stageFiles(list) { // Snapshot synchronously: `picker.files` and `dataTransfer.files` are LIVE // lists — clearing the picker or returning from the drop event empties @@ -122,6 +191,12 @@ async function stageFiles(list) { bytes: null, note: '', suspect: false, + findings: [], + profile: null, + preRecoveryProfile: readPreRecoveryProfile(file.name.endsWith('._') ? undefined : head), + retried: false, + companionUsed: false, + error: null, }); // same name re-dropped: replace // A re-dropped file restarts as staged; drop any stale row/output. if (old) removeRow(file.name, true); @@ -129,29 +204,77 @@ async function stageFiles(list) { render(); } +/** + * Pre-recovery profile from the header slice. + * + * This is pure presentation: it reports the observed target (`PE32+ · native + * DLL · header magic`) and never turns a metadata magic match into a + * protection claim. Returns `null` for companions and for anything the core + * cannot describe. + */ +function readPreRecoveryProfile(head) { + if (!head) return null; + try { + const parsed = JSON.parse(inspect_profile_json(head)); + return parsed && typeof parsed === 'object' ? parsed : null; + } catch { + return null; + } +} + /** Insert `.unpack` before the final extension: `app.exe` -> `app.unpack.exe`. */ function outName(name) { const dot = name.lastIndexOf('.'); return dot > 0 ? `${name.slice(0, dot)}.unpack${name.slice(dot)}` : `${name}.unpack`; } +/** + * Staged status line: the observed header facts, which is what the profile can + * say before any recovery runs. The kind label is only a fallback, because + * `describeObserved` already names the format and kind. + */ +function stagedStatus(entry) { + const label = KIND_LABEL[entry.kind] ?? entry.kind; + if (entry.kind === 'metadata') { + // The kind label names the file type; `observed` carries the version and + // the format-only disclaimer. + const observed = describeObserved(entry.preRecoveryProfile); + return observed ? `${label} — ${observed}` : label; + } + // A PE profile already names the format and kind, so dropping the kind from + // it avoids "protected native DLL — PE32+ · native DLL". + const observed = describeObserved(entry.preRecoveryProfile, { includeKind: false }); + return observed ? `${label} — ${observed}` : label; +} + function statusText(name, entry) { if (name.endsWith('._')) { return `companion — needs ${name.slice(0, -2)}`; } switch (entry.state) { case 'staged': - return entry.kind === undefined - ? 'not recognized — will be skipped' - : KIND_LABEL[entry.kind] ?? entry.kind; + if (entry.kind === undefined) return 'not recognized — will be skipped'; + if (isBlocked(name)) return 'above the input limit — will be skipped'; + return stagedStatus(entry); case 'working': - return 'unpacking…'; + return entry.kind === 'metadata' ? 'de-obfuscating…' : 'unpacking…'; case 'ok': case 'err': + case 'blocked': return entry.note; } } +/** + * Details block: profile stages and severity-labelled findings. + * + * The row's status line already carries the failure text, so the details list + * it only when it adds something the summary does not. + */ +function detailLines(entry) { + return [...describeStages(entry.profile), ...describeFindings(entry.findings)]; +} + function buildRow(name) { const li = document.createElement('li'); li.className = 'file staged'; @@ -185,6 +308,14 @@ function buildRow(name) { dl.hidden = true; row.appendChild(dl); + const report = document.createElement('button'); + report.type = 'button'; + report.className = 'report'; + report.textContent = '{}'; + report.title = `Export a JSON report for ${name}`; + report.addEventListener('click', () => exportOne(name)); + row.appendChild(report); + const rm = document.createElement('button'); rm.type = 'button'; rm.className = 'remove'; @@ -200,6 +331,12 @@ function buildRow(name) { row.appendChild(rm); li.appendChild(row); + + const details = document.createElement('ul'); + details.className = 'details'; + details.hidden = true; + li.appendChild(details); + return li; } @@ -219,6 +356,27 @@ function updateRow(li, name, entry) { li.querySelector('.status').textContent = statusText(name, entry); + const details = li.querySelector('.details'); + const lines = detailLines(entry); + details.hidden = lines.length === 0; + if (lines.length > 0) { + // Rebuild only when the text actually changed: writing identical children + // every render would restart the row's entrance animation. + const key = lines.join('\n'); + if (details.dataset.key !== key) { + details.replaceChildren( + ...lines.map((line) => { + const item = document.createElement('li'); + item.textContent = line; + if (line.startsWith('fatal:')) item.className = 'fatal'; + else if (line.startsWith('warning:')) item.className = 'warning'; + return item; + }), + ); + details.dataset.key = key; + } + } + const dl = li.querySelector('.dl'); const downloadable = entry.state === 'ok' && entry.bytes; dl.hidden = !downloadable; @@ -230,8 +388,8 @@ function updateRow(li, name, entry) { ); dl._bytesFor = entry.bytes; } - dl.download = outName(name); - dl.title = `Download ${outName(name)}`; + dl.download = entry.outputName ?? outName(name); + dl.title = `Download ${dl.download}`; } } @@ -264,6 +422,19 @@ function removeRow(name, instant) { } function render() { + budgetPlan = planReadBudget(stagedSizes(), limitBytes); + + // Raising the limit must un-block rows the previous limit skipped: a + // `blocked` row is a budget verdict, not a result, so it returns to + // `staged` once it fits again and the user can press Unpack. + for (const [name, entry] of files) { + if (entry.state === 'blocked' && !isBlocked(name)) { + entry.state = 'staged'; + entry.error = null; + entry.note = ''; + } + } + // Create/update rows in Map order; companions whose base is staged merge // into the base row (no row of their own). const wanted = []; @@ -284,7 +455,7 @@ function render() { // running animations (entrance, shimmer) are never restarted by a render. // Rows mid-leave-animation (no longer in rowEls) are skipped and keep // their spot — reordering siblings around them would make them snap - // instead of sliding with the collapse. + // instead of slide with the collapse. let cursor = fileList.firstChild; for (const name of wanted) { let li = rowEls.get(name); @@ -312,6 +483,16 @@ function render() { ); unpackBtn.disabled = !unpackable; actions.hidden = files.size === 0; + + // The hint reflects the current staged set: the budget's own guidance when + // it has something to say, otherwise the standing explanation. + if (budgetPlan && budgetPlan.guidance.length > 0) { + limitHint.textContent = budgetPlan.guidance.join(' '); + limitHint.classList.toggle('warn', budgetPlan.blocked.length > 0); + } else { + limitHint.textContent = LIMIT_BASE_HINT; + limitHint.classList.remove('warn'); + } } clearBtn.addEventListener('click', () => { @@ -320,11 +501,14 @@ clearBtn.addEventListener('click', () => { }); /** - * Run one unpack in a disposable Web Worker (fresh wasm instance per call — - * see worker.js). Buffers are transferred, so the inputs are neutered on the - * main thread afterwards; callers re-read from the File for a retry. + * Run one job in a disposable Web Worker (fresh wasm instance per call — see + * worker.js). Buffers are transferred, so the inputs are neutered on the main + * thread afterwards; callers re-read from the File for a retry. + * + * `job` is read eagerly, but `read()` only runs after the caller has checked + * the budget: no `arrayBuffer()` call happens here. */ -function runUnpack(inputBytes, compBytes, forceExe) { +function runJob(job) { return new Promise((resolve) => { const w = new Worker('worker.js', { type: 'module' }); w.onmessage = (e) => { @@ -333,45 +517,108 @@ function runUnpack(inputBytes, compBytes, forceExe) { }; w.onerror = (e) => { w.terminate(); - resolve({ ok: false, trap: true, message: e.message || 'worker error' }); + // A worker that fails to load (404, syntax error) reports no trap: the + // retry below must not rerun an identical broken job. + resolve({ ok: false, trap: false, message: e.message || 'worker error', profile: null }); }; - const transfer = [inputBytes.buffer, ...(compBytes ? [compBytes.buffer] : [])]; - w.postMessage({ input: inputBytes, companion: compBytes ?? null, forceExe }, transfer); + const transfer = [job.input.buffer, ...(job.companion ? [job.companion.buffer] : [])]; + w.postMessage(job, transfer); }); } +/** Read a File only after the budget check has allowed it. */ +async function readFile(file) { + return new Uint8Array(await file.arrayBuffer()); +} + +/** + * Apply one worker reply to a row, keeping the failure profile and error. + * + * The profile is stored even when the job failed: it names the route that ran + * and why it was rejected, which is what the exported report needs. + */ +function applyReply(entry, r) { + entry.profile = r.profile ?? entry.profile; + if (!r.ok) { + entry.state = 'err'; + entry.error = r.message ?? r.error ?? 'unpack failed'; + entry.findings = []; + entry.note = r.trap + ? 'unpack failed (internal trap) — this Crackproof layout may be unsupported' + : entry.error; + return false; + } + entry.findings = (r.issues ?? []).map((message, index) => ({ + severity: r.severities?.[index] === 'fatal' ? 'fatal' : 'warning', + message, + })); + entry.suspect = r.suspect === true; + entry.companionUsed = r.companion === true; + entry.error = null; + return true; +} + async function unpackModule(name, entry) { const compEntry = files.get(`${name}._`); - const read = (f) => f.arrayBuffer().then((b) => new Uint8Array(b)); - let input = await read(entry.file); - let comp = compEntry ? await read(compEntry.file) : undefined; - let r = await runUnpack(input, comp, false); + let input = await readFile(entry.file); + let comp = compEntry ? await readFile(compEntry.file) : undefined; + let r = await runJob({ mode: 'unpack', input, companion: comp ?? null, forceExe: false }); + let retried = false; const isExe = entry.kind === 'native-exe' || entry.kind === 'managed-exe'; if (!r.ok && r.trap && !isExe) { // The DLL-routing probe trapped (panics can't be caught in wasm). Retry // once with the forced-EXE pipeline in a fresh worker — this mirrors the // CLI's dll-first/exe-fallback outcome for EXE-shell-layout DLLs. - input = await read(entry.file); - comp = compEntry ? await read(compEntry.file) : undefined; - r = await runUnpack(input, comp, true); + input = await readFile(entry.file); + comp = compEntry ? await readFile(compEntry.file) : undefined; + r = await runJob({ mode: 'unpack', input, companion: comp ?? null, forceExe: true }); + retried = true; } + entry.retried = retried; - if (!r.ok) { + if (!applyReply(entry, r)) return; + entry.state = 'ok'; + entry.bytes = r.bytes; + entry.outputBytes = r.bytes.byteLength; + entry.outputName = outName(name); + const parts = []; + if (r.companion || comp) parts.push('spliced from ._ companion'); + parts.push(`kind: ${r.kind}`); + if (retried) parts.push('forced-EXE retry'); + if (entry.suspect) { + // The per-finding text lives in the details list; the status line only + // has to say how serious it is. + const fatal = entry.findings.filter((finding) => finding.severity === 'fatal').length; + const warnings = entry.findings.length - fatal; + const counts = [ + fatal > 0 ? `${fatal} fatal` : null, + warnings > 0 ? `${warnings} warning${warnings === 1 ? '' : 's'}` : null, + ].filter(Boolean).join(', '); + parts.push(`${r.fatal ? 'FAILED static check' : 'suspect'} (${counts})`); + } + entry.note = parts.join(' — '); +} + +async function unpackMetadata(name, entry) { + const input = await readFile(entry.file); + const r = await runJob({ mode: 'metadata', input }); + if (!applyReply(entry, r)) return; + const report = r.metadata ?? {}; + if (report.remapped === 0) { entry.state = 'err'; - entry.note = r.trap - ? 'unpack failed (internal trap) — this Crackproof layout may be unsupported' - : r.message; + entry.error = + `metadata already clean (v${report.version}, ${report.methods} methods) — nothing to do`; + entry.note = entry.error; return; } entry.state = 'ok'; entry.bytes = r.bytes; - entry.suspect = r.suspect; + entry.outputBytes = r.bytes.byteLength; + entry.outputName = outName(name); entry.note = - (r.companion ? 'spliced from ._ companion; ' : '') + - `kind: ${r.kind}` + - (r.suspect ? ` — SUSPECT: ${r.issues.join('; ')}` : ''); + `${report.remapped}/${report.methods} method tokens remapped across ${report.modules} modules`; } unpackBtn.addEventListener('click', async () => { @@ -383,7 +630,8 @@ unpackBtn.addEventListener('click', async () => { if (entry.kind === undefined) { entry.state = 'err'; - entry.note = 'not recognized as Crackproof-protected — skipped'; + entry.error = 'not recognized as Crackproof-protected — skipped'; + entry.note = entry.error; render(); continue; } @@ -392,26 +640,31 @@ unpackBtn.addEventListener('click', async () => { // status line already says to use the CLI. if (entry.kind.startsWith('android-')) continue; + // Budget gate. Runs before any read of the module body: `entry.file` + // has not been touched for bytes yet. A blocked module keeps its + // companion paired; only its own read is skipped. + if (isBlocked(name)) { + entry.state = 'blocked'; + entry.error = + `${name} is above the ${formatBytes(limitBytes)} input limit — raise the limit to unpack it`; + entry.note = entry.error; + render(); + continue; + } + entry.state = 'working'; render(); + entry.inputBytes = entry.file.size + (files.get(`${name}._`)?.file.size ?? 0); try { if (entry.kind === 'metadata') { - const bytes = new Uint8Array(await entry.file.arrayBuffer()); - const r = deobfuscate_metadata(bytes); - if (r.remapped === 0) { - entry.state = 'err'; - entry.note = `metadata already clean (v${r.version}, ${r.methods} methods) — nothing to do`; - } else { - entry.state = 'ok'; - entry.bytes = r.bytes; - entry.note = `${r.remapped}/${r.methods} method tokens remapped across ${r.modules} modules`; - } + await unpackMetadata(name, entry); } else { await unpackModule(name, entry); } } catch (e) { entry.state = 'err'; - entry.note = e instanceof Error ? e.message : String(e); + entry.error = e instanceof Error ? e.message : String(e); + entry.note = entry.error; } render(); } @@ -420,3 +673,51 @@ unpackBtn.addEventListener('click', async () => { render(); } }); + +// --- JSON export ---------------------------------------------------------- + +function downloadJson(name, text) { + const url = URL.createObjectURL(new Blob([text], { type: 'application/json' })); + const a = document.createElement('a'); + a.href = url; + a.download = name; + a.click(); + // Revoke on the next task: revoking synchronously can cancel the download + // in some browsers. + setTimeout(() => URL.revokeObjectURL(url), 0); +} + +function generatedAt() { + return new Date().toISOString(); +} + +/** + * Per-row export: one file's report in the same envelope as the all-files + * export, so a consumer parses one shape. The row's companion is included as + * `companion_used` only — the companion has no report of its own. + */ +function exportOne(name) { + const entry = files.get(name); + if (!entry) return; + const at = generatedAt(); + downloadJson( + reportFileName(name, at), + serializeReport(buildReport(new Map([[name, entry]]), { + generatedAt: at, + limitBytes, + includeNotes: true, + })), + ); +} + +exportBtn.addEventListener('click', () => { + const at = generatedAt(); + downloadJson( + reportFileName(null, at), + serializeReport(buildReport(files, { generatedAt: at, limitBytes, includeNotes: true })), + ); +}); + +// Paint the initial state so the limit hint and the action row are consistent +// before anything is staged. +render(); diff --git a/web/index.html b/web/index.html index 7a7cacc..1f03ed4 100644 --- a/web/index.html +++ b/web/index.html @@ -63,10 +63,18 @@ +
+ + +

+
+
    diff --git a/web/package.json b/web/package.json new file mode 100644 index 0000000..051ba02 --- /dev/null +++ b/web/package.json @@ -0,0 +1,9 @@ +{ + "name": "senbei-web", + "private": true, + "type": "module", + "description": "Static frontend for the senbei wasm build; no npm dependencies.", + "scripts": { + "test": "node --test tests/*.test.js" + } +} diff --git a/web/report.js b/web/report.js new file mode 100644 index 0000000..79c4751 --- /dev/null +++ b/web/report.js @@ -0,0 +1,397 @@ +// Pure helpers for the browser frontend: input memory budgeting and JSON +// report shaping. No DOM, no network, no clock reads — every function is a +// pure transform so `web/tests/` can exercise it under Node. + +/** Practical default ceiling for one staged input set (base + companion). */ +export const DEFAULT_INPUT_LIMIT_BYTES = 256 * 1024 * 1024; + +/** The limit control accepts this range; outside it the field is ignored. */ +export const MIN_INPUT_LIMIT_MIB = 8; +export const MAX_INPUT_LIMIT_MIB = 4096; + +/** Version of the browser report envelope this module emits. */ +export const REPORT_SCHEMA = 'senbei.browser-report'; +export const REPORT_SCHEMA_VERSION = 1; + +const MIB = 1024 * 1024; + +/** + * Parse the limit input (MiB) into bytes. + * + * Empty, non-numeric, or out-of-range input falls back to `fallback` so a + * half-typed value never changes the active budget mid-session. + */ +export function parseLimitMiB(raw, fallback = DEFAULT_INPUT_LIMIT_BYTES) { + const text = String(raw ?? '').trim(); + if (text === '') return fallback; + const mib = Number(text); + if (!Number.isFinite(mib)) return fallback; + if (mib < MIN_INPUT_LIMIT_MIB || mib > MAX_INPUT_LIMIT_MIB) return fallback; + return Math.round(mib) * MIB; +} + +/** Human byte size with one decimal for MiB/GiB steps. */ +export function formatBytes(bytes) { + if (!Number.isFinite(bytes) || bytes < 0) return '0 B'; + if (bytes < 1024) return `${bytes} B`; + if (bytes < MIB) return `${(bytes / 1024).toFixed(1)} KiB`; + if (bytes < 1024 * MIB) return `${(bytes / MIB).toFixed(1)} MiB`; + return `${(bytes / (1024 * MIB)).toFixed(2)} GiB`; +} + +/** True for the `._` companion suffix. */ +export function isCompanionName(name) { + return typeof name === 'string' && name.endsWith('._'); +} + +/** Base module name for a companion, or the name itself. */ +export function baseName(name) { + return isCompanionName(name) ? name.slice(0, -2) : name; +} + +/** + * Group staged entries into one budget unit per base module. + * + * A companion (`X._`) and its base (`X`) are read together by the unpack + * path, so they must be measured together; measuring them separately would + * let a 200 MiB pair pass a 200 MiB limit and then read 400 MiB. + * + * `entries` accepts `{ name, size }` objects or `File`-like values with + * `name` and `size`. + */ +export function groupByModule(entries) { + const groups = new Map(); + for (const entry of entries ?? []) { + const name = entry?.name; + if (typeof name !== 'string' || name === '') continue; + const size = Number(entry.size); + const base = baseName(name); + const group = groups.get(base) ?? { base, bytes: 0, names: [], companion: false }; + group.bytes += Number.isFinite(size) && size > 0 ? size : 0; + group.names.push(name); + if (isCompanionName(name)) group.companion = true; + groups.set(base, group); + } + return [...groups.values()]; +} + +/** + * Decide whether the staged set may be read into memory. + * + * This runs from `File.size` metadata BEFORE any `arrayBuffer()` call. It is a + * best-effort guard, not a peak-RSS guarantee: unpacking holds the input, the + * recovered image, and the pipeline's own scratch buffers at once, so the real + * peak is a multiple of the bytes measured here. + * + * Returns the blocked modules, the modules that compile a warning, and the + * combined-size guidance strings the UI shows verbatim. + */ +export function planReadBudget(entries, limitBytes, options = {}) { + const limit = Number.isFinite(limitBytes) && limitBytes > 0 + ? limitBytes + : DEFAULT_INPUT_LIMIT_BYTES; + const warnFactor = options.warnFactor ?? 0.5; + const groups = groupByModule(entries); + const totalBytes = groups.reduce((sum, group) => sum + group.bytes, 0); + const blocked = []; + const oversized = []; + for (const group of groups) { + if (group.bytes > limit) blocked.push(group); + else if (group.bytes >= limit * warnFactor) oversized.push(group); + } + const overLimit = groups.length > 0 && totalBytes > limit; + const blockedBases = blocked.map((group) => group.base); + const blockedNames = new Set(blocked.flatMap((group) => group.names)); + const guidance = []; + if (blocked.length > 0) { + for (const group of blocked) { + guidance.push( + `Skipped ${group.base} (${formatBytes(group.bytes)} with companion)` + + ` — above the ${formatBytes(limit)} input limit.`, + ); + } + } else if (overLimit) { + guidance.push( + `Staged inputs total ${formatBytes(totalBytes)}, above the ` + + `${formatBytes(limit)} limit. Unpack them one at a time, or raise the limit.`, + ); + } else if (totalBytes > 0) { + guidance.push( + `Staged inputs total ${formatBytes(totalBytes)}. Unpacking holds the ` + + 'input, the recovered image, and pipeline scratch buffers together, so ' + + 'transient memory use is several times this figure.', + ); + if (oversized.length > 0) { + const names = oversized.map((group) => group.base).join(', '); + guidance.push(`Near the ${formatBytes(limit)} limit: ${names}.`); + } + } + return { + limitBytes: limit, + totalBytes, + overLimit, + warnFactor, + groups, + /** Base module names that must not be read (their companion goes with them). */ + blocked: blockedBases, + /** Base module names that fit but are at least `warnFactor` of the limit. */ + nearLimit: oversized.map((group) => group.base), + guidance, + /** Base module names that may be read. */ + allowed: groups + .filter((group) => !blockedNames.has(group.base)) + .map((group) => group.base), + }; +} + +/** Sort findings fatal-first while keeping the checker's order within a class. */ +export function sortFindings(findings) { + const weight = (finding) => (finding?.severity === 'fatal' ? 0 : 1); + return (findings ?? []) + .filter((finding) => finding && typeof finding.message === 'string') + .map((finding, index) => ({ finding, index })) + .sort((a, b) => weight(a.finding) - weight(b.finding) || a.index - b.index) + .map(({ finding }) => ({ + severity: finding.severity === 'fatal' ? 'fatal' : 'warning', + message: finding.message, + })); +} + +/** `clean` / `warnings` / `failed` for a finding list. */ +export function integrityStatus(findings) { + const list = sortFindings(findings); + if (list.length === 0) return 'clean'; + return list.some((finding) => finding.severity === 'fatal') ? 'failed' : 'warnings'; +} + +/** The profile's own final static-check verdict, or `null` when absent. */ +export function profileIntegrityStatus(profile) { + const value = profile?.static_validation; + return value === 'clean' || value === 'warnings' || value === 'failed' || value === 'not_run' + ? value + : null; +} + +/** + * Integrity verdict for a recovered row. + * + * The profile records the check that actually ran, so it wins whenever it has + * a value. That matters for metadata: its transform is validated by the + * metadata adapter and the PE static check does not apply, so the profile says + * `not_run` — reporting `clean` there would invent a check that never + * happened. Without a profile, metadata still falls back to `not_run`; a PE + * row falls back to its findings, as before. + */ +export function recoveredIntegrityStatus(entry, findings) { + const fromProfile = profileIntegrityStatus(entry?.profile); + if (fromProfile !== null) return fromProfile; + if (entry?.kind === 'metadata') return 'not_run'; + return integrityStatus(findings); +} + +/** + * Per-file report entry. + * + * `entry` is the app's row state: `{ state, kind, outputName, inputBytes, + * outputBytes, findings, profile, preRecoveryProfile, companionUsed, retried, + * error, note }`. The full protection profile object (snake_case, + * `format_version`) is embedded verbatim under `profile` and + * `pre_recovery_profile`; only the browser envelope is versioned here. + */ +export function buildFileReport(name, entry, options = {}) { + const state = entry?.state ?? 'staged'; + const status = state === 'ok' + ? 'recovered' + : state === 'err' + ? 'failed' + : state === 'blocked' + ? 'blocked' + : 'pending'; + const findings = sortFindings(entry?.findings); + const report = { + name, + output_name: entry?.outputName ?? null, + status, + kind: entry?.kind ?? null, + input_bytes: Number.isFinite(entry?.inputBytes) ? entry.inputBytes : null, + output_bytes: Number.isFinite(entry?.outputBytes) ? entry.outputBytes : null, + companion_used: entry?.companionUsed === true, + forced_exe_retry: entry?.retried === true, + profile: entry?.profile ?? null, + pre_recovery_profile: entry?.preRecoveryProfile ?? null, + integrity: { + status: status === 'recovered' + ? recoveredIntegrityStatus(entry, findings) + : 'not_run', + findings, + }, + error: status === 'failed' || status === 'blocked' ? (entry?.error ?? null) : null, + }; + if (options.includeNotes && entry?.note) report.note = entry.note; + return report; +} + +/** + * All-files report envelope. `generatedAt` is passed in so the helper stays + * pure and the tests are deterministic. + */ +export function buildReport(entries, options = {}) { + const files = []; + for (const [name, entry] of entries ?? []) { + if (isCompanionName(name)) continue; + files.push(buildFileReport(name, entry, options)); + } + const recovered = files.filter((file) => file.status === 'recovered').length; + const failed = files.filter((file) => file.status === 'failed').length; + const blocked = files.filter((file) => file.status === 'blocked').length; + return { + schema: REPORT_SCHEMA, + schema_version: REPORT_SCHEMA_VERSION, + generated_at: options.generatedAt ?? null, + input_limit_bytes: Number.isFinite(options.limitBytes) ? options.limitBytes : null, + summary: { files: files.length, recovered, failed, blocked }, + files, + }; +} + +/** Serialize a report deterministically (2-space indent, trailing newline). */ +export function serializeReport(report) { + return `${JSON.stringify(report, null, 2)}\n`; +} + +/** + * Download file name for a report. + * + * `generatedAt` is an ISO timestamp; only `YYYYMMDD-HHMMSS` survives, so the + * name is filesystem-safe on Windows and stable across time zones. + */ +export function reportFileName(name, generatedAt) { + const stamp = String(generatedAt ?? '') + .replace(/\D/g, '') + .slice(0, 14) + .replace(/^(\d{8})(\d{6})$/, '$1-$2'); + if (!name) return stamp ? `senbei-${stamp}.report.json` : 'senbei-report.json'; + const base = baseName(name).replace(/\.(exe|dll|dat)$/i, ''); + // Windows/macOS-safe: no path separators, colons, or spaces. + const stem = base.replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^_+|_+$/g, '') || 'senbei'; + return stamp ? `${stem}.${stamp}.report.json` : `${stem}.report.json`; +} + +// --- Profile presentation ------------------------------------------------- +// +// The profile reports only observed facts. These helpers must never turn a +// magic-byte match into a protection claim: `recognition` says whether the +// header key table matched, `recovery` whether a route produced an image, and +// `static_validation` whether that image passed the structural checks. + +const FORMAT_LABEL = { + pe32: 'PE32', + pe32_plus: 'PE32+', + elf64_aarch64: 'ELF64 AArch64', + il2cpp_metadata: 'il2cpp metadata', +}; + +const KIND_LABEL = { + native_exe: 'native EXE', + managed_exe: 'managed EXE', + native_dll: 'native DLL', + managed_dll: 'managed DLL', +}; + +const LAYOUT_LABEL = { + dll: 'DLL layout', + exe_style: 'EXE-style layout', + android_staged: 'Android staged', + metadata_structural: 'metadata structural', + metadata_seeded: 'metadata seeded', + metadata_method_indices: 'metadata method indices', +}; + +const EVIDENCE_LABEL = { + header_magic: 'header magic', + external_companion_declaration: 'external companion declared', + companion_spliced: 'companion spliced', + private_section: 'private loader section', + aes_schedule: 'AES schedule', + validated_metadata_transform: 'metadata transform validated', +}; + +function humanize(value) { + return String(value ?? '').replace(/_/g, ' '); +} + +/** + * One-line description of an observed target, used before recovery runs. + * + * For metadata the text says explicitly that the version identifies a format, + * not a protection. + */ +export function describeObserved(profile, options = {}) { + if (!profile || typeof profile !== 'object') return ''; + const observed = profile.observed ?? {}; + if (observed.platform === 'il2cpp_metadata') { + // The format name is already the row's kind label, so repeat only the + // version. The disclaimer is mandatory: identify() matches a format + // header, and a format header is not evidence of protection. + const version = observed.metadata_version != null + ? `v${observed.metadata_version}` + : 'version unknown'; + return `${version} · format only, not a protection verdict`; + } + const parts = []; + const format = FORMAT_LABEL[observed.format] ?? humanize(observed.format); + if (format) parts.push(format); + if (options.includeKind !== false) { + const kind = KIND_LABEL[observed.kind] ?? humanize(observed.kind); + if (kind) parts.push(kind); + } + if (observed.external_companion) parts.push('external companion'); + const head = parts.join(' · '); + const evidence = (profile.evidence ?? []) + .map((value) => EVIDENCE_LABEL[value] ?? humanize(value)) + .join(', '); + if (head && evidence) return `${head} · ${evidence}`; + return head || evidence; +} + +/** + * Route/validation lines for a finished (or failed) recovery. + * + * The PE static check does not apply to metadata output, so its + * `static check not run` line is omitted for metadata profiles rather than + * shown as a missing step. + */ +export function describeStages(profile) { + if (!profile || typeof profile !== 'object') return []; + const lines = []; + const selected = profile.selected ? (LAYOUT_LABEL[profile.selected] ?? humanize(profile.selected)) : null; + if (Array.isArray(profile.candidates)) { + for (const attempt of profile.candidates) { + if (!attempt || typeof attempt !== 'object') continue; + const layout = LAYOUT_LABEL[attempt.layout] ?? humanize(attempt.layout); + const outcome = humanize(attempt.outcome); + const suffix = selected && attempt.layout === profile.selected ? ' — selected' : ''; + lines.push(`${layout}: ${outcome}${suffix}`); + } + } + // Only a run of the static check is worth a line. `not_run` covers both the + // failed recovery (no image to check) and metadata output (the PE check does + // not apply), and in both cases the row's status already says so. + const validation = profile.static_validation; + if (validation && validation !== 'not_run') { + const label = validation === 'clean' + ? 'static check clean' + : validation === 'warnings' + ? 'static check with warnings' + : 'static check failed'; + lines.push(label); + } + return lines; +} + +/** Severity-labelled integrity lines: fatal first, then warnings. */ +export function describeFindings(findings) { + return sortFindings(findings).map( + (finding) => `${finding.severity === 'fatal' ? 'fatal' : 'warning'}: ${finding.message}`, + ); +} diff --git a/web/style.css b/web/style.css index 47cfab0..414e2ff 100644 --- a/web/style.css +++ b/web/style.css @@ -224,6 +224,8 @@ code { .file.ok { background: var(--ok); } .file.ok.suspect { background: #6b5a1e; } .file.err { background: var(--err); } +/* Over the input limit: nothing was read, so this is not a failure. */ +.file.blocked { background: #3c3520; border-color: var(--warn); } .file .row { position: relative; @@ -239,7 +241,7 @@ code { } .file.working .name { color: #fff; } -.file.ok .name, .file.err .name { color: #fff; } +.file.ok .name, .file.err .name, .file.blocked .name { color: #fff; } .badge.companion { flex: none; @@ -269,6 +271,7 @@ code { .file.ok .status { color: #cfe9d5; } .file.ok.suspect .status { color: #f0e3b2; } .file.err .status { color: #f0c8c8; } +.file.blocked .status { color: #f2e2b0; } .file.working .status { color: #dbe7ff; } .file .dl { @@ -309,6 +312,7 @@ code { .file.ok .remove, .file.err .remove, +.file.blocked .remove, .file.working .remove { border-color: rgba(255, 255, 255, 0.3); color: rgba(255, 255, 255, 0.75); @@ -326,6 +330,104 @@ code { animation: fadeIn 0.25s ease-out; } +/* --- input limit --- */ + +.limits { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 0.5rem 0.75rem; + margin: 0 0 1rem; + font-size: 0.9rem; + color: var(--dim); +} + +.limits label { flex: none; } + +#limit-mib { + width: 7rem; + padding: 0.35rem 0.5rem; + font: inherit; + color: var(--text); + background: var(--panel); + border: 1px solid var(--border); + border-radius: 6px; +} + +#limit-mib:focus-visible { + outline: none; + border-color: var(--accent); +} + +.limits .hint { + flex-basis: 100%; + margin: 0; +} + +.limits .hint.warn { color: var(--warn); } + +/* --- per-row report detail --- */ + +.file .details { + list-style: none; + margin: 0; + padding: 0 0.85rem 0.55rem; + font-size: 0.8rem; + color: var(--dim); +} + +.file .details li { + overflow-wrap: anywhere; + padding-left: 0.9rem; + position: relative; +} + +.file .details li::before { + content: '·'; + position: absolute; + left: 0.2rem; + opacity: 0.7; +} + +.file.ok .details, .file.err .details, .file.working .details { color: #d8dde5; } +.file .details li.fatal { color: var(--err-bright); } +.file .details li.warning { color: var(--warn); } +.file.ok .details li.fatal { color: #ffb3b3; } + +.file .report { + flex: none; + padding: 0.1rem 0.45rem; + font-family: ui-monospace, Consolas, monospace; + font-size: 0.8rem; + font-weight: 400; + background: transparent; + border: 1px solid var(--border); + border-radius: 6px; + color: var(--dim); +} + +.file .report:hover { + color: var(--text); + border-color: var(--accent); + box-shadow: none; + transform: none; +} + +.file.ok .report, +.file.err .report, +.file.blocked .report, +.file.working .report { + border-color: rgba(255, 255, 255, 0.3); + color: rgba(255, 255, 255, 0.8); +} + +.file.ok .report:hover, +.file.err .report:hover, +.file.blocked .report:hover { + color: #fff; + border-color: #fff; +} + footer { margin-top: 2rem; color: var(--dim); diff --git a/web/tests/report.test.js b/web/tests/report.test.js new file mode 100644 index 0000000..3c76093 --- /dev/null +++ b/web/tests/report.test.js @@ -0,0 +1,504 @@ +// Node tests for the pure frontend helpers in web/report.js. +// +// Run with: node --test web/tests/ +// No dependencies: `node:test` and `node:assert/strict` are built in. + +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { + DEFAULT_INPUT_LIMIT_BYTES, + MAX_INPUT_LIMIT_MIB, + MIN_INPUT_LIMIT_MIB, + REPORT_SCHEMA, + REPORT_SCHEMA_VERSION, + buildFileReport, + buildReport, + describeFindings, + describeObserved, + describeStages, + formatBytes, + groupByModule, + integrityStatus, + isCompanionName, + parseLimitMiB, + planReadBudget, + reportFileName, + serializeReport, + sortFindings, +} from '../report.js'; + +const MiB = 1024 * 1024; +const file = (name, size) => ({ name, size }); + +test('parseLimitMiB keeps a usable typed value and rejects the rest', () => { + assert.equal(parseLimitMiB('128'), 128 * MiB); + assert.equal(parseLimitMiB(' 64 '), 64 * MiB); + assert.equal(parseLimitMiB('8'), MIN_INPUT_LIMIT_MIB * MiB); + assert.equal(parseLimitMiB(String(MAX_INPUT_LIMIT_MIB)), MAX_INPUT_LIMIT_MIB * MiB); +}); + +test('parseLimitMiB falls back for empty, junk, and out-of-range input', () => { + for (const raw of [undefined, null, '', ' ', 'abc', '12abc', '-4', '0', '7', '4097', 'Infinity']) { + assert.equal(parseLimitMiB(raw), DEFAULT_INPUT_LIMIT_BYTES, `raw=${String(raw)}`); + } + const custom = 32 * MiB; + assert.equal(parseLimitMiB('', custom), custom); + assert.equal(parseLimitMiB('999999', custom), custom); +}); + +test('formatBytes scales through the units', () => { + assert.equal(formatBytes(0), '0 B'); + assert.equal(formatBytes(999), '999 B'); + assert.equal(formatBytes(1024), '1.0 KiB'); + assert.equal(formatBytes(3 * MiB), '3.0 MiB'); + assert.equal(formatBytes(1.5 * 1024 * MiB), '1.50 GiB'); + assert.equal(formatBytes(-1), '0 B'); + assert.equal(formatBytes(Number.NaN), '0 B'); +}); + +test('companion detection and base naming', () => { + assert.equal(isCompanionName('game.exe._'), true); + assert.equal(isCompanionName('game.exe'), false); + assert.equal(isCompanionName(undefined), false); + assert.equal(groupByModule([file('a.exe', 1)]).length, 1); +}); + +test('groupByModule sums a module and its companion into one budget unit', () => { + const groups = groupByModule([ + file('game.exe', 10 * MiB), + file('game.exe._', 90 * MiB), + file('other.dll', 5 * MiB), + ]); + assert.equal(groups.length, 2); + const game = groups.find((group) => group.base === 'game.exe'); + assert.equal(game.bytes, 100 * MiB); + assert.equal(game.companion, true); + assert.deepEqual(game.names.sort(), ['game.exe', 'game.exe._']); + const other = groups.find((group) => group.base === 'other.dll'); + assert.equal(other.companion, false); +}); + +test('groupByModule ignores junk entries instead of throwing', () => { + const groups = groupByModule([null, {}, { name: '' }, { name: 'x.exe' }, file('y.exe', -5)]); + assert.deepEqual(groups.map((group) => group.base).sort(), ['x.exe', 'y.exe']); + assert.equal(groups.find((group) => group.base === 'y.exe').bytes, 0); + assert.deepEqual(groupByModule(undefined), []); +}); + +test('planReadBudget blocks a module whose base+companion exceed the limit', () => { + const plan = planReadBudget( + [file('game.exe', 10 * MiB), file('game.exe._', 90 * MiB), file('small.dll', 4 * MiB)], + 64 * MiB, + ); + assert.equal(plan.limitBytes, 64 * MiB); + assert.equal(plan.overLimit, true); + assert.deepEqual([...plan.blocked], ['game.exe']); + assert.deepEqual(plan.allowed, ['small.dll']); + assert.equal(plan.guidance.length, 1); + assert.match(plan.guidance[0], /Skipped game\.exe \(100\.0 MiB with companion\)/); + assert.match(plan.guidance[0], /64\.0 MiB input limit/); +}); + +test('planReadBudget flags modules near the limit but still allows them', () => { + const plan = planReadBudget([file('app.dll', 40 * MiB)], 64 * MiB); + assert.deepEqual([...plan.blocked], []); + assert.deepEqual(plan.nearLimit, ['app.dll']); + assert.deepEqual(plan.allowed, ['app.dll']); + assert.match(plan.guidance[0], /Unpacking holds the input/); + assert.match(plan.guidance[1], /Near the 64\.0 MiB limit: app\.dll/); +}); + +test('planReadBudget allows the whole set when nothing is oversized', () => { + const plan = planReadBudget([file('a.exe', 2 * MiB), file('b.dll', 3 * MiB)], 64 * MiB); + assert.equal(plan.overLimit, false); + assert.deepEqual(plan.allowed.sort(), ['a.exe', 'b.dll']); + assert.match(plan.guidance[0], /Staged inputs total 5\.0 MiB/); +}); + +test('planReadBudget guidance is best-effort, never a peak-RSS claim', () => { + const plan = planReadBudget([file('a.exe', 8 * MiB)], 64 * MiB); + const text = plan.guidance.join(' '); + assert.match(text, /several times this figure/); + assert.doesNotMatch(text, /peak|guarantee|exactly/i); +}); + +test('planReadBudget with an empty or invalid limit uses the default', () => { + const plan = planReadBudget([file('a.exe', 1 * MiB)], Number.NaN); + assert.equal(plan.limitBytes, DEFAULT_INPUT_LIMIT_BYTES); + assert.deepEqual(planReadBudget([], 64 * MiB).guidance, []); +}); + +test('planReadBudget with no entries blocks and allows nothing', () => { + const plan = planReadBudget([], 64 * MiB); + assert.equal(plan.totalBytes, 0); + assert.equal(plan.overLimit, false); + assert.deepEqual(plan.allowed, []); + assert.deepEqual(plan.guidance, []); +}); + +test('sortFindings puts fatal first and is stable within a severity', () => { + const sorted = sortFindings([ + { severity: 'warning', message: 'w1' }, + { severity: 'fatal', message: 'f1' }, + { severity: 'warning', message: 'w2' }, + { severity: 'fatal', message: 'f2' }, + ]); + assert.deepEqual(sorted.map((finding) => finding.message), ['f1', 'f2', 'w1', 'w2']); +}); + +test('sortFindings normalizes unknown severities to warning and drops junk', () => { + const sorted = sortFindings([ + { severity: 'FATAL', message: 'upper' }, + { severity: 'fatal', message: 'lower' }, + null, + { message: 'no severity' }, + ]); + assert.deepEqual(sorted, [ + { severity: 'fatal', message: 'lower' }, + { severity: 'warning', message: 'upper' }, + { severity: 'warning', message: 'no severity' }, + ]); +}); + +test('integrityStatus separates clean, warnings, and failed', () => { + assert.equal(integrityStatus([]), 'clean'); + assert.equal(integrityStatus(undefined), 'clean'); + assert.equal(integrityStatus([{ severity: 'warning', message: 'w' }]), 'warnings'); + assert.equal( + integrityStatus([ + { severity: 'warning', message: 'w' }, + { severity: 'fatal', message: 'f' }, + ]), + 'failed', + ); +}); + +test('buildFileReport maps a success row without inventing protection claims', () => { + const report = buildFileReport('game.exe', { + state: 'ok', + kind: 'native-dll', + outputName: 'game.unpack.exe', + inputBytes: 100 * MiB, + outputBytes: 120 * MiB, + companionUsed: true, + retried: true, + findings: [{ severity: 'warning', message: 'no base relocations' }], + profile: { format_version: 1, recovery: 'succeeded' }, + preRecoveryProfile: { format_version: 1, recognition: 'recognized' }, + }); + assert.equal(report.status, 'recovered'); + assert.equal(report.output_name, 'game.unpack.exe'); + assert.equal(report.companion_used, true); + assert.equal(report.forced_exe_retry, true); + assert.equal(report.integrity.status, 'warnings'); + assert.equal(report.integrity.findings.length, 1); + assert.equal(report.error, null); + assert.equal(report.profile.format_version, 1); + assert.equal(report.pre_recovery_profile.recognition, 'recognized'); +}); + +test('buildFileReport keeps metadata integrity at not_run when the transform remapped', () => { + const report = buildFileReport('global-metadata.dat', { + state: 'ok', + kind: 'metadata', + outputName: 'global-metadata.unpack.dat', + findings: [], + profile: { + format_version: 1, + observed: { platform: 'il2cpp_metadata', metadata_version: 31 }, + evidence: ['validated_metadata_transform'], + recognition: 'recognized', + recovery: 'succeeded', + // The PE static check does not apply to metadata output. + static_validation: 'not_run', + }, + }); + assert.equal(report.status, 'recovered'); + assert.equal(report.integrity.status, 'not_run'); + assert.equal(report.integrity.findings.length, 0); +}); + +test('buildFileReport keeps metadata integrity at not_run when already clean', () => { + const report = buildFileReport('global-metadata.dat', { + state: 'ok', + kind: 'metadata', + findings: [], + profile: { + format_version: 1, + observed: { platform: 'il2cpp_metadata', metadata_version: 31 }, + recognition: 'not_recognized', + recovery: 'not_attempted', + static_validation: 'not_run', + warnings: ['metadata is already de-obfuscated; no tokens were rewritten'], + }, + }); + assert.equal(report.status, 'recovered'); + assert.equal(report.integrity.status, 'not_run'); + assert.doesNotMatch(serializeReport({ files: [report] }), /"status": "clean"/); +}); + +test('buildFileReport does not fabricate clean for metadata without a profile', () => { + const report = buildFileReport('global-metadata.dat', { + state: 'ok', + kind: 'metadata', + findings: [], + profile: null, + }); + assert.equal(report.integrity.status, 'not_run'); + assert.equal(report.profile, null); +}); + +test('buildFileReport keeps the PE finding fallback when the profile has no verdict', () => { + const fallback = buildFileReport('plain.dll', { + state: 'ok', + kind: 'native-dll', + findings: [{ severity: 'warning', message: 'no base relocations' }], + profile: { format_version: 1, recovery: 'succeeded' }, + }); + assert.equal(fallback.integrity.status, 'warnings'); + + const clean = buildFileReport('plain.exe', { + state: 'ok', + kind: 'native-exe', + findings: [], + profile: null, + }); + assert.equal(clean.integrity.status, 'clean'); +}); + +test('buildFileReport prefers the profile verdict over row findings', () => { + const warned = buildFileReport('app.exe', { + state: 'ok', + kind: 'native-exe', + findings: [], + profile: { format_version: 1, static_validation: 'warnings' }, + }); + assert.equal(warned.integrity.status, 'warnings'); + + const failed = buildFileReport('app.exe', { + state: 'ok', + kind: 'native-exe', + findings: [{ severity: 'fatal', message: 'unmapped entry point' }], + profile: { format_version: 1, static_validation: 'failed' }, + }); + assert.equal(failed.integrity.status, 'failed'); + assert.equal(failed.integrity.findings[0].severity, 'fatal'); +}); + +test('buildFileReport keeps the failure profile and error for a failed row', () => { + const report = buildFileReport('bad.dll', { + state: 'err', + error: 'not a Crackproof-protected file', + findings: [{ severity: 'fatal', message: 'unmapped entry point' }], + profile: { format_version: 1, recovery: 'failed', errors: ['boom'] }, + }); + assert.equal(report.status, 'failed'); + assert.equal(report.error, 'not a Crackproof-protected file'); + assert.equal(report.integrity.status, 'not_run'); + assert.equal(report.integrity.findings[0].severity, 'fatal'); + assert.equal(report.profile.recovery, 'failed'); +}); + +test('buildFileReport marks a budget-blocked row as blocked, not failed', () => { + const report = buildFileReport('huge.exe', { state: 'blocked', error: 'above input limit' }); + assert.equal(report.status, 'blocked'); + assert.equal(report.error, 'above input limit'); + assert.equal(report.integrity.status, 'not_run'); +}); + +test('buildFileReport leaves a staged row pending with no error', () => { + const report = buildFileReport('x.exe', { state: 'staged' }); + assert.equal(report.status, 'pending'); + assert.equal(report.error, null); + assert.equal(report.kind, null); +}); + +test('buildReport skips companion rows and counts statuses', () => { + const entries = new Map([ + ['a.exe', { state: 'ok', findings: [] }], + ['b.dll', { state: 'err', error: 'np' }], + ['c.dll', { state: 'blocked', error: 'big' }], + ['d.exe', { state: 'staged' }], + ['a.exe._', { state: 'staged' }], + ]); + const report = buildReport(entries, { + generatedAt: '2026-11-05T12:34:56.789Z', + limitBytes: 64 * MiB, + }); + assert.equal(report.schema, REPORT_SCHEMA); + assert.equal(report.schema_version, REPORT_SCHEMA_VERSION); + assert.equal(report.generated_at, '2026-11-05T12:34:56.789Z'); + assert.equal(report.input_limit_bytes, 64 * MiB); + assert.deepEqual(report.summary, { files: 4, recovered: 1, failed: 1, blocked: 1 }); + assert.deepEqual(report.files.map((entry) => entry.name), ['a.exe', 'b.dll', 'c.dll', 'd.exe']); +}); + +test('serializeReport is stable and newline-terminated', () => { + const report = buildReport(new Map(), { generatedAt: null }); + const text = serializeReport(report); + assert.ok(text.endsWith('\n')); + assert.equal(text, `${JSON.stringify(report, null, 2)}\n`); + assert.equal(serializeReport(report), text); +}); + +test('reportFileName is filesystem-safe and stamped', () => { + assert.equal( + reportFileName('game.exe', '2026-11-05T12:34:56.789Z'), + 'game.20261105-123456.report.json', + ); + assert.equal(reportFileName('game.exe._', '2026-11-05T12:34:56.789Z'), + 'game.20261105-123456.report.json'); + assert.equal(reportFileName(null, '2026-11-05T12:34:56.789Z'), + 'senbei-20261105-123456.report.json'); + assert.equal(reportFileName('game.exe', null), 'game.report.json'); + assert.equal(reportFileName(null, null), 'senbei-report.json'); + assert.doesNotMatch(reportFileName('a b.exe', '2026-11-05T12:34:56.789Z'), /[:\\/\s]/); +}); + +test('describeObserved never claims protection from a metadata magic match', () => { + const text = describeObserved({ + observed: { + platform: 'il2cpp_metadata', + format: 'il2cpp_metadata', + kind: null, + metadata_version: 31, + external_companion: false, + }, + evidence: [], + recognition: 'recognized', + }); + assert.equal(text, 'v31 · format only, not a protection verdict'); + assert.doesNotMatch(text, /protected|recognized|Crackproof|CrackProof/); +}); + +test('describeObserved lists PE target facts and evidence', () => { + const text = describeObserved({ + observed: { + platform: 'windows_pe', + format: 'pe32_plus', + kind: 'native_dll', + metadata_version: null, + external_companion: true, + }, + evidence: ['header_magic', 'companion_spliced'], + }); + assert.equal( + text, + 'PE32+ · native DLL · external companion · header magic, companion spliced', + ); +}); + +test('describeObserved tolerates an absent profile', () => { + assert.equal(describeObserved(null), ''); + assert.equal(describeObserved(undefined), ''); + assert.equal(describeObserved({}), ''); +}); + +test('describeStages reports candidate outcomes and the static check', () => { + const lines = describeStages({ + recovery: 'succeeded', + candidates: [ + { layout: 'dll', outcome: 'rejected', warnings: [], errors: ['bad'] }, + { layout: 'exe_style', outcome: 'succeeded', warnings: [], errors: [] }, + ], + selected: 'exe_style', + static_validation: 'warnings', + }); + assert.deepEqual(lines, [ + 'DLL layout: rejected', + 'EXE-style layout: succeeded — selected', + 'static check with warnings', + ]); +}); + +test('describeStages handles metadata routes and a failed check', () => { + const lines = describeStages({ + recovery: 'failed', + candidates: [{ layout: 'metadata_structural', outcome: 'failed' }], + selected: null, + static_validation: 'failed', + }); + assert.deepEqual(lines, ['metadata structural: failed', 'static check failed']); + assert.deepEqual(describeStages(null), []); +}); + +test('describeFindings labels severity', () => { + assert.deepEqual( + describeFindings([ + { severity: 'warning', message: 'w' }, + { severity: 'fatal', message: 'f' }, + ]), + ['fatal: f', 'warning: w'], + ); + assert.deepEqual(describeFindings(undefined), []); +}); + +test('describeStages omits the PE static check for metadata profiles', () => { + const lines = describeStages({ + observed: { platform: 'il2cpp_metadata' }, + recovery: 'succeeded', + candidates: [{ layout: 'metadata_structural', outcome: 'succeeded' }], + selected: 'metadata_structural', + static_validation: 'not_run', + }); + assert.deepEqual(lines, ['metadata structural: succeeded — selected']); +}); + +test('describeStages only shows a static check that actually ran', () => { + const recovered = describeStages({ + observed: { platform: 'windows_pe' }, + recovery: 'succeeded', + candidates: [{ layout: 'exe_style', outcome: 'succeeded' }], + selected: 'exe_style', + static_validation: 'clean', + }); + assert.deepEqual(recovered, ['EXE-style layout: succeeded — selected', 'static check clean']); + + // No check ran: the failure line already carries the reason, so a "not run" + // entry would be noise. + const failed = describeStages({ + observed: { platform: 'windows_pe' }, + recovery: 'blocked', + candidates: [{ layout: 'exe_style', outcome: 'not_attempted' }], + selected: null, + static_validation: 'not_run', + }); + assert.deepEqual(failed, ['EXE-style layout: not attempted']); +}); + +test('describeObserved can omit the kind it repeats from the row label', () => { + const profile = { + observed: { + platform: 'windows_pe', + format: 'pe32_plus', + kind: 'native_dll', + external_companion: false, + }, + evidence: ['header_magic'], + }; + assert.equal( + describeObserved(profile, { includeKind: false }), + 'PE32+ · header magic', + ); + assert.equal(describeObserved(profile), 'PE32+ · native DLL · header magic'); +}); + +test('buildFileReport carries the forced-EXE retry and failure profile', () => { + const report = buildFileReport('shell.dll', { + state: 'err', + retried: true, + error: 'structurally invalid layout candidate', + profile: { + format_version: 1, + candidates: [ + { layout: 'dll', outcome: 'failed' }, + { layout: 'exe_style', outcome: 'rejected' }, + ], + recovery: 'failed', + }, + }); + assert.equal(report.forced_exe_retry, true); + assert.equal(report.profile.candidates[1].outcome, 'rejected'); + assert.equal(report.status, 'failed'); +}); diff --git a/web/worker.js b/web/worker.js index 94ce10d..5c00d8c 100644 --- a/web/worker.js +++ b/web/worker.js @@ -1,7 +1,8 @@ -// One-shot unpack worker: each unpack runs in a fresh worker with its own -// wasm instance. Two reasons: +// One-shot worker: each job runs in a fresh worker with its own wasm instance. +// Two reasons: // -// 1. UI stays responsive — unpacking a 100 MB+ module blocks for seconds. +// 1. UI stays responsive — unpacking a 100 MB+ module (or rewriting a large +// `global-metadata.dat`) blocks for seconds. // 2. Trap isolation — the senbei DLL-first routing probe relies on // catch_unwind to reject EXE-shell-layout DLLs, and panics cannot be // caught in WebAssembly: the probe traps the whole call. A trap kills @@ -9,33 +10,88 @@ // retries with the forced-EXE pipeline in a NEW worker (the trapped // instance is never reused). That reproduces the CLI's // dll-first/exe-fallback routing without a catchable panic. +// +// Every reply carries the recovery profile (see `profile_json`), including +// failures: the page shows which route ran and why it was rejected. -import init, { unpack_file, unpack_file_force_exe } from './pkg/senbei_wasm.js'; +import init, { + deobfuscate_metadata_reported, + unpack_file_reported, +} from './pkg/senbei_wasm.js'; let ready = null; +/** Parse the profile JSON into a plain object for structured cloning. */ +function profileOf(doc) { + if (!doc) return null; + try { + return JSON.parse(doc); + } catch { + return null; + } +} + +/** Post a failure reply, keeping the trap flag the main thread retries on. */ +function postFailure(err, profile) { + const trap = err instanceof WebAssembly.RuntimeError; + self.postMessage({ + ok: false, + trap, + message: String(err?.message ?? err), + profile, + }); +} + self.onmessage = async (e) => { - const { input, companion, forceExe } = e.data; + const { mode, input, companion, forceExe } = e.data; + let profile = null; try { ready ??= init(); await ready; - const r = forceExe - ? unpack_file_force_exe(input, companion ?? undefined) - : unpack_file(input, companion ?? undefined); + + if (mode === 'metadata') { + const r = deobfuscate_metadata_reported(input); + profile = profileOf(r.profile_json); + const bytes = r.bytes; + self.postMessage( + { + ok: r.ok, + mode: 'metadata', + metadata: { + version: r.version, + methods: r.methods, + remapped: r.remapped, + modules: r.modules, + }, + error: r.error ?? null, + profile, + bytes, + }, + r.ok ? [bytes.buffer] : [], + ); + return; + } + + const r = unpack_file_reported(input, companion ?? undefined, forceExe === true); + profile = profileOf(r.profile_json); const bytes = r.bytes; self.postMessage( { - ok: true, + ok: r.ok, + mode: 'unpack', kind: r.kind, suspect: r.suspect, issues: r.issues, + severities: r.severities, + fatal: r.fatal, companion: r.companion, + error: r.error ?? null, + profile, bytes, }, - [bytes.buffer], + r.ok ? [bytes.buffer] : [], ); } catch (err) { - const trap = err instanceof WebAssembly.RuntimeError; - self.postMessage({ ok: false, trap, message: String(err?.message ?? err) }); + postFailure(err, profile); } };