From 21236e8b98588e3dcf237e303caae6589319975c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=B6=BE=E7=80=AC=E6=A1=83=E6=A1=83?= Date: Wed, 18 Nov 2026 17:10:12 +0800 Subject: [PATCH] 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. --- .github/workflows/ci.yml | 11 +- .github/workflows/release.yml | 5 +- senbei-cli/tests/android_samples.rs | 76 + senbei-cli/tests/wasm_parity.rs | 496 +++-- senbei-cli/tests/wasm_parity_driver.mjs | 139 +- senbei-engine/src/android/extract/mod.rs | 5 +- senbei-engine/src/android/extract/pipeline.rs | 367 +++- senbei-engine/src/android/mod.rs | 10 +- senbei-engine/src/android/restore/artifact.rs | 79 + senbei-engine/src/android/restore/mod.rs | 3 +- senbei-engine/src/android/restore/pipeline.rs | 1030 ++++++++--- senbei-gui/src/ui/dialogs.rs | 404 +++-- senbei-gui/src/ui/mod.rs | 12 +- senbei-io/src/android/memory.rs | 334 ++++ senbei-io/src/android/mod.rs | 11 +- senbei-io/src/job.rs | 33 +- senbei-io/src/report.rs | 28 + senbei-wasm/Cargo.lock | 2 + senbei-wasm/Cargo.toml | 21 + senbei-wasm/src/lib.rs | 1056 ++++++----- web/README.md | 41 +- web/app.js | 1610 ++++++++++------- web/assets/Asul-Bold.woff2 | Bin 0 -> 13396 bytes web/assets/Asul-OFL.txt | 94 + web/assets/check.svg | 1 + web/assets/icon-128.png | Bin 0 -> 17521 bytes web/assets/icon-32.png | Bin 0 -> 2293 bytes web/detail.js | 852 +++++++++ web/engine.js | 196 ++ web/i18n.js | 60 + web/i18n/en.js | 268 +++ web/i18n/ja.js | 268 +++ web/i18n/ko.js | 268 +++ web/i18n/web-strings.json | 121 ++ web/i18n/zh-CN.js | 268 +++ web/i18n/zh-TW.js | 268 +++ web/index.html | 108 +- web/model.js | 311 ++++ web/output.js | 149 ++ web/package.js | 99 + web/report.js | 642 +++---- web/run.js | 494 +++++ web/scan.js | 89 + web/state.js | 251 +++ web/style.css | 921 +++++----- web/tests/archives.js | 69 + web/tests/model.test.js | 208 +++ web/tests/output.test.js | 153 ++ web/tests/page.test.js | 473 +++++ web/tests/report.test.js | 786 ++++---- web/tests/scan.test.js | 209 +++ web/tests/zip.test.js | 137 ++ web/text.js | 96 + web/tools/gen-i18n.mjs | 183 ++ web/tools/stage.mjs | 46 + web/ui.js | 238 +++ web/view.js | 326 ++++ web/worker.js | 235 ++- web/zip.js | 388 ++++ 59 files changed, 11612 insertions(+), 3436 deletions(-) create mode 100644 senbei-io/src/android/memory.rs create mode 100644 web/assets/Asul-Bold.woff2 create mode 100644 web/assets/Asul-OFL.txt create mode 100644 web/assets/check.svg create mode 100644 web/assets/icon-128.png create mode 100644 web/assets/icon-32.png create mode 100644 web/detail.js create mode 100644 web/engine.js create mode 100644 web/i18n.js create mode 100644 web/i18n/en.js create mode 100644 web/i18n/ja.js create mode 100644 web/i18n/ko.js create mode 100644 web/i18n/web-strings.json create mode 100644 web/i18n/zh-CN.js create mode 100644 web/i18n/zh-TW.js create mode 100644 web/model.js create mode 100644 web/output.js create mode 100644 web/package.js create mode 100644 web/run.js create mode 100644 web/scan.js create mode 100644 web/state.js create mode 100644 web/tests/archives.js create mode 100644 web/tests/model.test.js create mode 100644 web/tests/output.test.js create mode 100644 web/tests/page.test.js create mode 100644 web/tests/scan.test.js create mode 100644 web/tests/zip.test.js create mode 100644 web/text.js create mode 100644 web/tools/gen-i18n.mjs create mode 100644 web/tools/stage.mjs create mode 100644 web/ui.js create mode 100644 web/view.js create mode 100644 web/zip.js diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 390f6f6..f7b4610 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -114,14 +114,11 @@ jobs: run: cargo test --release -p senbei-cli --test wasm_parity env: SENBEI_WASM_PARITY: '1' + - name: Stage static site + run: node web/tools/stage.mjs dist - uses: actions/upload-artifact@v4 with: name: senbei-web - path: | - web/index.html - web/app.js - web/report.js - web/worker.js - web/style.css - web/pkg/ + path: dist/ + if-no-files-found: error retention-days: 14 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 461b0a2..834f2bf 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -73,10 +73,7 @@ jobs: - run: wasm-pack build --target web --release --out-dir ../web/pkg -- --locked working-directory: senbei-wasm - name: Stage static site - run: | - mkdir dist - cp web/index.html web/app.js web/report.js web/worker.js web/style.css dist/ - cp -r web/pkg dist/pkg + run: node web/tools/stage.mjs dist - uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} diff --git a/senbei-cli/tests/android_samples.rs b/senbei-cli/tests/android_samples.rs index f6a13d2..d86ba00 100644 --- a/senbei-cli/tests/android_samples.rs +++ b/senbei-cli/tests/android_samples.rs @@ -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 = 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")); +} diff --git a/senbei-cli/tests/wasm_parity.rs b/senbei-cli/tests/wasm_parity.rs index 2a38ec6..7bb660b 100644 --- a/senbei-cli/tests/wasm_parity.rs +++ b/senbei-cli/tests/wasm_parity.rs @@ -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=`: every `pe`/`metadata` case in //! that harness manifest is also compared, still without writing any output. +//! With `SENBEI_ANDROID_SAMPLES=` 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 = 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::>(), + "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) { + let mut entries: Vec = 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 = 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"] diff --git a/senbei-cli/tests/wasm_parity_driver.mjs b/senbei-cli/tests/wasm_parity_driver.mjs index 2b45426..a695307 100644 --- a/senbei-cli/tests/wasm_parity_driver.mjs +++ b/senbei-cli/tests/wasm_parity_driver.mjs @@ -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": "", "companion": "|null" } -// Result: { "ok": true, "kind": ..., "bytes": , "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. } diff --git a/senbei-engine/src/android/extract/mod.rs b/senbei-engine/src/android/extract/mod.rs index a835992..baf1735 100644 --- a/senbei-engine/src/android/extract/mod.rs +++ b/senbei-engine/src/android/extract/mod.rs @@ -6,7 +6,10 @@ mod stage1; mod stream; pub use error::Error; -pub use pipeline::{ExtractOptions, extract_stage2, extract_stage2_with_limits}; +pub use pipeline::{ + ExtractOptions, MemoryExtraction, extract_stage2, extract_stage2_in_memory, + extract_stage2_with_limits, +}; pub use probe::{ is_protected_libil2cpp, is_protected_libil2cpp_profiled, probe_libil2cpp_profiled_with_limits, probe_libil2cpp_with_limits, record_android_recovered, diff --git a/senbei-engine/src/android/extract/pipeline.rs b/senbei-engine/src/android/extract/pipeline.rs index 4964720..c6b70d3 100644 --- a/senbei-engine/src/android/extract/pipeline.rs +++ b/senbei-engine/src/android/extract/pipeline.rs @@ -1,5 +1,6 @@ use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::fs::File; +use std::ops::Range; use std::path::{Path, PathBuf}; use memmap2::MmapOptions; @@ -70,8 +71,26 @@ struct DecodeBudget { config: Module9bConfig, } +/// Where decoded and direct stage-2 artifacts go. +enum Sink { + /// Content-named files under one directory, indexed by `index.json`. + Disk(PathBuf), + /// Nothing is written. Decoded images stay in the module registry, and a + /// direct record is remembered as its byte range in the protected input. + Memory(BTreeMap>), +} + +/// How one artifact relates to the protected input. +#[derive(Clone, Copy)] +enum Origin { + /// Decoded from a container into its own buffer. + Decoded, + /// A verbatim slice of the input that starts at this file offset. + Direct(usize), +} + struct Extractor { - output_dir: PathBuf, + sink: Sink, streams: Vec, artifacts: Vec, registry: BTreeMap, @@ -116,19 +135,123 @@ pub fn extract_stage2_with_limits( // lifetime, and extraction never mutates or truncates the source. let source = unsafe { MmapOptions::new().map(&file) } .map_err(|source| Error::io("map protected ELF", &input_path, source))?; - let stage1 = inspect( + let (stage1, extractor) = run_extraction( &source, &input_path, options.outer_size, options.cipher_constant, + limits, + Sink::Disk(output_dir.clone()), + |plaintext| match &options.stage2_output { + Some(stage2_output) => write_atomic(&absolute(stage2_output)?, plaintext), + None => Ok(()), + }, + )?; + let (report, _) = extractor.into_report( + stage1, + input_path.display().to_string(), + output_dir.display().to_string(), + ); + write_json_atomic(&output_dir.join("index.json"), &report)?; + Ok(report) +} + +/// A complete Stage 2 extraction that wrote nothing. +/// +/// Decoded module images are owned here. A direct record stays a byte range of +/// the protected input, so the caller keeps that input alive for as long as it +/// reads artifacts. The report has the same records as an on-disk extraction. +/// Its artifact names identify entries and are not files. Streams and direct +/// records have an empty `sha256`: their bytes are ranges of the input and are +/// not hashed. +#[derive(Debug)] +pub struct MemoryExtraction { + pub report: ExtractionReport, + modules: BTreeMap>, + direct: BTreeMap>, +} + +impl MemoryExtraction { + /// The decoded image of module `command_id`. + #[must_use] + pub fn module(&self, command_id: u32) -> Option<&[u8]> { + self.modules.get(&command_id).map(Vec::as_slice) + } + + /// The bytes of one reported artifact image. + /// + /// `input` is the protected ELF this extraction was made from. + pub(crate) fn image<'a>( + &'a self, + input: &'a [u8], + command_id: u32, + direct: bool, + name: &str, + ) -> Option<&'a [u8]> { + if direct { + input.get(self.direct.get(name)?.clone()) + } else { + self.module(command_id) + } + } +} + +/// [`extract_stage2_with_limits`] over bytes, writing nothing. +/// +/// The same decoding and the same budgets; the artifact files and +/// `index.json` are absent. See [`MemoryExtraction`] for how its report +/// differs. +pub fn extract_stage2_in_memory(input: &[u8], limits: &ResourceLimits) -> Result { + let (stage1, extractor) = run_extraction( + input, + Path::new(""), + DEFAULT_OUTER_SIZE, + DEFAULT_CIPHER_CONSTANT, + limits, + Sink::Memory(BTreeMap::new()), + |_| Ok(()), + )?; + let (report, extractor) = + extractor.into_report(stage1, "".to_owned(), "".to_owned()); + let direct = match extractor.sink { + Sink::Memory(direct) => direct, + Sink::Disk(_) => BTreeMap::new(), + }; + Ok(MemoryExtraction { + report, + modules: extractor + .registry + .into_iter() + .map(|(command_id, module)| (command_id, module.image)) + .collect(), + direct, + }) +} + +/// Decode Stage 1 and every Stage 2 stream of `source` into `sink`. +/// +/// `stage2_plaintext` sees the decrypted Stage 1 payload before any stream is +/// decoded, which is where the on-disk driver saves it when asked to. +fn run_extraction( + source: &[u8], + input_path: &Path, + outer_size: usize, + cipher_constant: u32, + limits: &ResourceLimits, + sink: Sink, + stage2_plaintext: impl FnOnce(&[u8]) -> Result<()>, +) -> Result<(Stage1Report, Extractor)> { + let stage1 = inspect( + source, + input_path, + outer_size, + cipher_constant, // Stage 1 plaintext is the first thing this task retains. Its copy // is capped by both the single-entry ceiling and whatever remains of // the task total, which is the whole total at this point. Some(limits.max_entry_bytes.min(limits.max_total_bytes)), )?; - if let Some(stage2_output) = &options.stage2_output { - write_atomic(&absolute(stage2_output)?, &stage1.plaintext)?; - } + stage2_plaintext(&stage1.plaintext)?; let core_config = Module9bConfig::parse_embedded(&stage1.plaintext).map_err(Error::EmbeddedConfig)?; @@ -140,7 +263,7 @@ pub fn extract_stage2_with_limits( .get(stage1.remaining_file_offset..bootstrap_end) .ok_or_else(|| Error::Invalid("Stage 2 bootstrap range is outside the ELF".to_owned()))?; let mut extractor = Extractor { - output_dir: output_dir.clone(), + sink, streams: Vec::new(), artifacts: Vec::new(), registry: BTreeMap::new(), @@ -157,60 +280,97 @@ pub fn extract_stage2_with_limits( .charge(u64::try_from(stage1.plaintext.len()).unwrap_or(u64::MAX))?; extractor.extract_stream( bootstrap, - 0xe2, - 0, - None, - Some(stage1.remaining_file_offset), + StreamPlace { + stream_id: 0xe2, + depth: 0, + parent: None, + source_file_offset: Some(stage1.remaining_file_offset), + base: stage1.remaining_file_offset, + }, &mut budget, )?; + Ok((stage1_report(&stage1, outer_size), extractor)) +} - let module_registry = extractor - .registry - .values() - .map(|module| ModuleRegistryEntry { - command_id: module.command_id, - size: module.image.len(), - sha256: module.sha256.clone(), - depth: module.depth, - record_index: module.record_index, - image_path: module.image_path.clone(), - metadata_path: module.metadata_path.clone(), - init_offset: module.init_offset, - entry_offset: module.entry_offset, - classification: if module.metadata.is_some() { - "module_image".to_owned() - } else { - "decoded_data".to_owned() - }, - }) - .collect::>(); - let report = ExtractionReport { - format_version: 4, - protected_elf: input_path.display().to_string(), - output_dir: output_dir.display().to_string(), - stage1: stage1_report(&stage1, options.outer_size), - streams: extractor.streams, - artifacts: extractor.artifacts, - errors: Vec::new(), - module_registry, - }; - write_json_atomic(&output_dir.join("index.json"), &report)?; - Ok(report) +/// Where one record stream sits: its identity, its nesting, and the file +/// offset of its first byte in the protected input. +struct StreamPlace { + stream_id: u32, + depth: usize, + parent: Option, + /// Reported for the bootstrap stream only. + source_file_offset: Option, + base: usize, } impl Extractor { + /// Close the extraction: the report, and the extractor with its registry. + fn into_report( + mut self, + stage1: Stage1Report, + protected_elf: String, + output_dir: String, + ) -> (ExtractionReport, Self) { + let module_registry = self + .registry + .values() + .map(|module| ModuleRegistryEntry { + command_id: module.command_id, + size: module.image.len(), + sha256: module.sha256.clone(), + depth: module.depth, + record_index: module.record_index, + image_path: module.image_path.clone(), + metadata_path: module.metadata_path.clone(), + init_offset: module.init_offset, + entry_offset: module.entry_offset, + classification: if module.metadata.is_some() { + "module_image".to_owned() + } else { + "decoded_data".to_owned() + }, + }) + .collect::>(); + let report = ExtractionReport { + format_version: 4, + protected_elf, + output_dir, + stage1, + streams: std::mem::take(&mut self.streams), + artifacts: std::mem::take(&mut self.artifacts), + errors: Vec::new(), + module_registry, + }; + (report, self) + } + fn extract_stream( &mut self, stream: &[u8], - stream_id: u32, - depth: usize, - parent: Option, - source_file_offset: Option, + place: StreamPlace, budget: &mut DecodeBudget, ) -> Result<()> { + let StreamPlace { + stream_id, + depth, + parent, + source_file_offset, + base, + } = place; budget.limits.check_depth(depth)?; - let digest = sha256(stream); - if !self.seen_streams.insert((stream_id, digest.clone())) { + // A stream is extracted once. On disk it is identified by content, and + // the digest goes into the report. In memory every stream is a range + // of the one input, so its position identifies it: each nested stream + // spans most of the payload, and hashing them all would read a large + // library several times over. + let (digest, identity) = match &self.sink { + Sink::Disk(_) => { + let digest = sha256(stream); + (digest.clone(), digest) + } + Sink::Memory(_) => (String::new(), format!("@{base:x}+{:x}", stream.len())), + }; + if !self.seen_streams.insert((stream_id, identity)) { return Ok(()); } let (header, records, table_size) = @@ -288,6 +448,7 @@ impl Extractor { classification, }, &image, + Origin::Decoded, )?; result.image = Some(artifact.clone()); image_data = Some((image, artifact)); @@ -319,6 +480,7 @@ impl Extractor { classification: "decoded_metadata", }, &metadata, + Origin::Decoded, )?; result.metadata = Some(artifact.clone()); metadata_data = Some((metadata, artifact)); @@ -368,6 +530,7 @@ impl Extractor { classification: "direct_data", }, direct_data, + Origin::Direct(direct_base(base, record.image_offset)?), )?; stream_report.records[report_index].image = Some(artifact); } @@ -398,10 +561,13 @@ impl Extractor { let parent_config = std::mem::replace(&mut budget.config, interpreter_config); self.extract_stream( child_data, - next_stream_id, - depth + 1, - Some(parent), - None, + StreamPlace { + stream_id: next_stream_id, + depth: depth + 1, + parent: Some(parent), + source_file_offset: None, + base: direct_base(base, record.image_offset)?, + }, budget, )?; budget.config = parent_config; @@ -430,24 +596,37 @@ impl Extractor { stream_id: u32, spec: ArtifactSpec<'_>, data: &[u8], + origin: Origin, ) -> Result { - let digest = sha256(data); + // A direct record kept in memory is a range of the input, which the + // caller already holds. Hashing it would read the largest payload in + // the file a second time only to name it, so it gets a positional name + // and no digest. + let digest = match (&self.sink, origin) { + (Sink::Memory(_), Origin::Direct(_)) => String::new(), + _ => sha256(data), + }; let filename = format!( "d{depth:02}_s{stream_id:02X}_r{:03}_id{:08X}_{}.{}", record.index, record.command_id, - &digest[..12], + digest.get(..12).unwrap_or("input"), spec.suffix ); - let path = self.output_dir.join(filename); - write_atomic(&path, data)?; + match &mut self.sink { + Sink::Disk(output_dir) => write_atomic(&output_dir.join(&filename), data)?, + Sink::Memory(direct) => { + if let Origin::Direct(start) = origin { + let end = start.checked_add(data.len()).ok_or_else(|| { + Error::Invalid("direct artifact range overflows usize".to_owned()) + })?; + direct.insert(filename.clone(), start..end); + } + } + } let artifact = ArtifactReport { kind: spec.kind.to_owned(), - path: path - .file_name() - .ok_or_else(|| Error::Invalid("artifact path has no file name".to_owned()))? - .to_string_lossy() - .into_owned(), + path: filename, size: data.len(), sha256: digest, depth, @@ -513,6 +692,15 @@ fn record_slice(stream: &[u8], offset: u32, size: u32) -> Result<&[u8]> { }) } +/// File offset of a direct payload that starts `offset` bytes into a stream +/// whose first byte is at `base`. +fn direct_base(base: usize, offset: u32) -> Result { + usize::try_from(offset) + .ok() + .and_then(|offset| base.checked_add(offset)) + .ok_or_else(|| Error::Invalid("direct payload file offset overflows usize".to_owned())) +} + fn record_tail(stream: &[u8], offset: u32) -> Result<&[u8]> { let offset = usize::try_from(offset) .map_err(|_| Error::Invalid("record container offset exceeds usize".to_owned()))?; @@ -670,7 +858,7 @@ mod limit_tests { fn extractor() -> Extractor { Extractor { - output_dir: PathBuf::from("."), + sink: Sink::Memory(BTreeMap::new()), streams: Vec::new(), artifacts: Vec::new(), registry: BTreeMap::new(), @@ -678,6 +866,16 @@ mod limit_tests { } } + fn place(stream_id: u32, depth: usize) -> StreamPlace { + StreamPlace { + stream_id, + depth, + parent: None, + source_file_offset: None, + base: 0, + } + } + fn budget(entries: usize, depth: usize) -> DecodeBudget { let limits = tight(entries, depth); DecodeBudget { @@ -692,7 +890,7 @@ mod limit_tests { fn record_budget_rejects_one_past_the_ceiling_and_allows_the_boundary() { let stream = direct_stream(0xe2, &[0]); let error = extractor() - .extract_stream(&stream, 0xe2, 0, None, None, &mut budget(0, 32)) + .extract_stream(&stream, place(0xe2, 0), &mut budget(0, 32)) .expect_err("one record is already past a zero-record ceiling"); assert!( matches!( @@ -705,26 +903,22 @@ mod limit_tests { "unexpected error: {error}" ); - let directory = tempfile::tempdir().expect("temporary output directory"); let mut at_ceiling = extractor(); - at_ceiling.output_dir = directory.path().to_path_buf(); at_ceiling - .extract_stream(&stream, 0xe2, 0, None, None, &mut budget(1, 0)) + .extract_stream(&stream, place(0xe2, 0), &mut budget(1, 0)) .expect("one record at depth zero is the boundary"); } #[test] fn nesting_one_past_the_ceiling_is_rejected_before_the_child_is_decoded() { let stream = direct_stream(0xe2, &[0]); - let directory = tempfile::tempdir().expect("temporary output directory"); let mut at_ceiling = extractor(); - at_ceiling.output_dir = directory.path().to_path_buf(); at_ceiling - .extract_stream(&stream, 0xe2, 32, None, None, &mut budget(1, 32)) + .extract_stream(&stream, place(0xe2, 32), &mut budget(1, 32)) .expect("depth 32 is the nesting boundary"); let error = extractor() - .extract_stream(&stream, 0xe2, 33, None, None, &mut budget(1, 32)) + .extract_stream(&stream, place(0xe2, 33), &mut budget(1, 32)) .expect_err("depth 33 is rejected before the stream is parsed"); match &error { Error::Limit(limit) => assert_eq!( @@ -741,7 +935,6 @@ mod limit_tests { #[test] fn decoded_payloads_share_one_task_budget() { let stream = direct_stream(0xe2, &[0]); - let directory = tempfile::tempdir().expect("temporary output directory"); let mut budget = budget(1, 0); budget.limits.max_total_bytes = 1; budget.bytes = ByteBudget::new(&budget.limits); @@ -750,11 +943,39 @@ mod limit_tests { // one the caller passed in and is not reset per stream. budget.bytes.charge(1).unwrap(); let mut extractor = extractor(); - extractor.output_dir = directory.path().to_path_buf(); extractor - .extract_stream(&stream, 0xe2, 0, None, None, &mut budget) + .extract_stream(&stream, place(0xe2, 0), &mut budget) .unwrap(); assert_eq!(budget.bytes.used(), 1); assert!(budget.bytes.charge(1024).is_err()); } + + #[test] + fn a_direct_record_is_remembered_as_its_range_in_the_input() { + // The stream starts 0x40 bytes into the input, as a bootstrap stream + // starts after the Stage 1 payload. + let payload = b"direct payload bytes"; + let stream = direct_stream(0xe2, payload); + let mut input = vec![0xaa_u8; 0x40]; + input.extend_from_slice(&stream); + + let mut extractor = extractor(); + let mut place = place(0xe2, 0); + place.base = 0x40; + extractor + .extract_stream(&stream, place, &mut budget(1, 0)) + .unwrap(); + + let Sink::Memory(direct) = &extractor.sink else { + panic!("the test extractor keeps artifacts in memory"); + }; + let artifact = &extractor.artifacts[0]; + assert_eq!(artifact.kind, "direct"); + let range = direct[&artifact.path].clone(); + assert_eq!(&input[range], payload); + assert!( + extractor.registry.is_empty(), + "a direct record is not copied" + ); + } } diff --git a/senbei-engine/src/android/mod.rs b/senbei-engine/src/android/mod.rs index 22905ad..905d770 100644 --- a/senbei-engine/src/android/mod.rs +++ b/senbei-engine/src/android/mod.rs @@ -7,15 +7,15 @@ mod restore; pub use extract::{ DEFAULT_CIPHER_CONSTANT, DEFAULT_OUTER_SIZE, Error as ExtractionError, ExtractOptions, - ExtractionReport, extract_stage2, extract_stage2_with_limits, is_protected_libil2cpp, - is_protected_libil2cpp_profiled, probe_libil2cpp_profiled_with_limits, - probe_libil2cpp_with_limits, record_android_recovered, + ExtractionReport, MemoryExtraction, extract_stage2, extract_stage2_in_memory, + extract_stage2_with_limits, is_protected_libil2cpp, is_protected_libil2cpp_profiled, + probe_libil2cpp_profiled_with_limits, probe_libil2cpp_with_limits, record_android_recovered, }; pub use limits::{ ByteBudget, DEFAULT_MAX_DEPTH, DEFAULT_MAX_ENTRIES, DEFAULT_MAX_ENTRY_BYTES, DEFAULT_MAX_TOTAL_BYTES, EntryBudget, LimitExceeded, ResourceLimits, }; pub use restore::{ - Error as RestoreError, RestoreOptions, RestoreReport, restore_libil2cpp, - restore_libil2cpp_with_limits, + Error as RestoreError, RestoreOptions, RestoreReport, RestoredImage, restore_libil2cpp, + restore_libil2cpp_in_memory, restore_libil2cpp_with_limits, }; diff --git a/senbei-engine/src/android/restore/artifact.rs b/senbei-engine/src/android/restore/artifact.rs index 0282356..16426f4 100644 --- a/senbei-engine/src/android/restore/artifact.rs +++ b/senbei-engine/src/android/restore/artifact.rs @@ -117,3 +117,82 @@ pub(crate) fn load_artifacts(index_path: &Path) -> Result { + pub data: &'a [u8], + pub entry_offset: Option, +} + +/// [`load_artifacts`] for an extraction that wrote nothing. +/// +/// The same precedence as the on-disk index: the module registry first, then +/// every stream record in report order, a later record replacing an earlier +/// one with the same command ID. `input` is the protected ELF the extraction +/// was made from; direct records are slices of it. +pub(crate) fn memory_artifacts<'a>( + extraction: &'a crate::android::extract::MemoryExtraction, + input: &'a [u8], +) -> Result>> { + let report = &extraction.report; + let mut result = BTreeMap::new(); + let mut resolve = + |command_id: u32, direct: bool, name: &str, size: usize, entry_offset: u32| -> Result<()> { + if !wanted_id(command_id) { + return Ok(()); + } + let data = extraction + .image(input, command_id, direct, name) + .filter(|data| data.len() == size) + .ok_or_else(|| { + Error::Invalid(format!( + "invalid artifact for module 0x{command_id:02X}: {name}" + )) + })?; + result.insert( + command_id, + MemoryArtifact { + data, + entry_offset: Some(entry_offset), + }, + ); + Ok(()) + }; + for module in &report.module_registry { + resolve( + module.command_id, + false, + &module.image_path, + module.size, + module.entry_offset, + )?; + } + for stream in &report.streams { + for record in &stream.records { + let Some(image) = &record.image else { + continue; + }; + resolve( + record.command_id, + record.direct, + &image.path, + image.size, + record.entry_offset, + )?; + } + } + + let missing = REQUIRED_IDS + .iter() + .filter(|id| !result.contains_key(id)) + .map(|id| format!("0x{id:02X}")) + .collect::>(); + if !missing.is_empty() { + return invalid(format!( + "module index lacks required IDs: {}", + missing.join(", ") + )); + } + Ok(result) +} diff --git a/senbei-engine/src/android/restore/mod.rs b/senbei-engine/src/android/restore/mod.rs index d894006..5ce3df5 100644 --- a/senbei-engine/src/android/restore/mod.rs +++ b/senbei-engine/src/android/restore/mod.rs @@ -6,5 +6,6 @@ mod verify; pub use error::Error; pub use pipeline::{ - RestoreOptions, RestoreReport, restore_libil2cpp, restore_libil2cpp_with_limits, + RestoreOptions, RestoreReport, RestoredImage, restore_libil2cpp, restore_libil2cpp_in_memory, + restore_libil2cpp_with_limits, }; diff --git a/senbei-engine/src/android/restore/pipeline.rs b/senbei-engine/src/android/restore/pipeline.rs index 0f7b5d4..5d669c0 100644 --- a/senbei-engine/src/android/restore/pipeline.rs +++ b/senbei-engine/src/android/restore/pipeline.rs @@ -14,9 +14,10 @@ use sha2::{Digest, Sha256}; use tempfile::NamedTempFile; use super::super::common; -use super::artifact::load_artifacts; +use super::artifact::{load_artifacts, memory_artifacts}; use super::error::{Error, Result, invalid}; -use crate::android::{ByteBudget, ResourceLimits}; +use crate::android::extract::MemoryExtraction; +use crate::android::{ByteBudget, EntryBudget, ResourceLimits}; use senbei_elf::{ DT_GNU_HASH, DT_HASH, DT_JMPREL, DT_PLTRELSZ, DT_RELA, DT_RELACOUNT, DT_RELASZ, DT_STRSZ, DT_STRTAB, DT_SYMTAB, DT_VERNEED, DT_VERSYM, ELF64_RELA_SIZE, ELF64_SYMBOL_SIZE, ElfLayout, @@ -2326,7 +2327,7 @@ fn materialize_static_elf_tables( )) } -fn write_padding(file: &mut File, size: u64, path: &Path) -> Result<()> { +fn write_padding(file: &mut impl Write, size: u64, path: &Path) -> Result<()> { const ZEROES: [u8; 4096] = [0; 4096]; let mut remaining = size; while remaining != 0 { @@ -2339,13 +2340,19 @@ fn write_padding(file: &mut File, size: u64, path: &Path) -> Result<()> { Ok(()) } -fn finalize_clean_elf( - stream: &mut File, +/// Append the retained non-loaded sections and a section-header table after +/// `data_start`, then point the ELF header at them. +/// +/// `sync` makes the finished stream durable; an in-memory image has nothing +/// to do there. +fn finalize_clean_elf( + stream: &mut S, temporary_path: &Path, source: &[u8], layout: &ElfLayout, data_start: u64, preserve_entrypoint: bool, + sync: impl FnOnce(&mut S) -> std::io::Result<()>, ) -> Result { let private = layout.private_section()?; if data_start < private.offset { @@ -2413,7 +2420,7 @@ fn finalize_clean_elf( .map_err(|error| Error::io("patch ELF header", temporary_path, error))?; stream .flush() - .and_then(|_| stream.sync_all()) + .and_then(|_| sync(stream)) .map_err(|error| Error::io("flush temporary output", temporary_path, error))?; Ok(CleaningReport { private_section_index: layout.private_section_index, @@ -2514,6 +2521,582 @@ fn write_atomic(path: &Path, data: &[u8]) -> Result<()> { common::write_atomic(path, data).map_err(|error| Error::io("write temporary file", path, error)) } +/// The restored image while it is being built, on disk or in memory. +/// +/// Both drivers run the same restoration over it, so their bytes are the same. +trait OutputImage { + /// Begin the image as a copy of `prefix`: the input up to its private + /// section. `reserve` estimates the bytes appended later. + fn start(&mut self, prefix: &[u8], reserve: u64) -> Result<()>; + + /// Extend with zeroes, or truncate, to `length` bytes. + fn set_len(&mut self, length: u64, action: &'static str) -> Result<()>; + + /// Run `edit` over the first `length` bytes. + fn edit(&mut self, length: usize, edit: impl FnOnce(&mut [u8]) -> Result) -> Result; + + /// Append the retained sections and the section-header table. + fn finalize( + &mut self, + source: &[u8], + layout: &ElfLayout, + data_start: u64, + preserve_entrypoint: bool, + ) -> Result; + + /// Run `read` over the finished image. + fn view(&mut self, read: impl FnOnce(&[u8]) -> Result) -> Result; +} + +/// A private temporary file beside the destination, renamed over it at the end. +struct DiskOutput { + parent: PathBuf, + temporary: Option<(NamedTempFile, PathBuf)>, +} + +impl DiskOutput { + fn opened(&mut self) -> Result<(&mut NamedTempFile, &Path)> { + match &mut self.temporary { + Some((temporary, path)) => Ok((temporary, path.as_path())), + None => invalid("temporary output was not created"), + } + } + + fn persist(self, output_path: &Path) -> Result<()> { + let Some((temporary, _)) = self.temporary else { + return invalid("temporary output was not created"); + }; + temporary + .persist(output_path) + .map_err(|error| Error::io("replace restored output", output_path, error.error))?; + Ok(()) + } +} + +impl OutputImage for DiskOutput { + fn start(&mut self, prefix: &[u8], _reserve: u64) -> Result<()> { + std::fs::create_dir_all(&self.parent) + .map_err(|error| Error::io("create output directory", &self.parent, error))?; + let mut temporary = NamedTempFile::new_in(&self.parent) + .map_err(|error| Error::io("create temporary output", &self.parent, error))?; + let temporary_path = temporary.path().to_path_buf(); + copy_range( + prefix, + temporary.as_file_mut(), + prefix.len(), + &temporary_path, + )?; + temporary + .as_file_mut() + .flush() + .map_err(|error| Error::io("flush initial output", &temporary_path, error))?; + self.temporary = Some((temporary, temporary_path)); + Ok(()) + } + + fn set_len(&mut self, length: u64, action: &'static str) -> Result<()> { + let (temporary, path) = self.opened()?; + temporary + .as_file() + .set_len(length) + .map_err(|error| Error::io(action, path, error)) + } + + fn edit(&mut self, length: usize, edit: impl FnOnce(&mut [u8]) -> Result) -> Result { + let (temporary, path) = self.opened()?; + let mut output = map_mut(temporary.as_file(), length, path)?; + let result = edit(&mut output)?; + output + .flush() + .map_err(|error| Error::io("flush restored image", path, error))?; + Ok(result) + } + + fn finalize( + &mut self, + source: &[u8], + layout: &ElfLayout, + data_start: u64, + preserve_entrypoint: bool, + ) -> Result { + let (temporary, path) = self.opened()?; + finalize_clean_elf( + temporary.as_file_mut(), + path, + source, + layout, + data_start, + preserve_entrypoint, + |file| file.sync_all(), + ) + } + + fn view(&mut self, read: impl FnOnce(&[u8]) -> Result) -> Result { + let (temporary, path) = self.opened()?; + let restored = map_read_only(temporary.as_file(), path)?; + read(&restored) + } +} + +/// One growable buffer. Used where there is no filesystem to map. +#[derive(Default)] +struct MemoryOutput { + bytes: Vec, +} + +impl MemoryOutput { + fn label() -> &'static Path { + Path::new("") + } + + fn reserve(&mut self, additional: usize) -> Result<()> { + self.bytes + .try_reserve_exact(additional) + .map_err(|_| Error::Invalid("restored image reservation failed".to_owned())) + } +} + +impl OutputImage for MemoryOutput { + fn start(&mut self, prefix: &[u8], reserve: u64) -> Result<()> { + // One reservation for the whole image keeps a later growth from + // copying it. The estimate is a hint: when it cannot be met, the + // prefix alone is reserved and later steps grow the buffer. + let wanted = usize::try_from(reserve) + .ok() + .and_then(|reserve| prefix.len().checked_add(reserve)); + if wanted.is_none_or(|wanted| self.bytes.try_reserve_exact(wanted).is_err()) { + self.reserve(prefix.len())?; + } + self.bytes.extend_from_slice(prefix); + Ok(()) + } + + fn set_len(&mut self, length: u64, _action: &'static str) -> Result<()> { + let length = usize_from_u64(length, "restored image length")?; + if let Some(additional) = length.checked_sub(self.bytes.len()) { + self.reserve(additional)?; + } + self.bytes.resize(length, 0); + Ok(()) + } + + fn edit(&mut self, length: usize, edit: impl FnOnce(&mut [u8]) -> Result) -> Result { + let image = self.bytes.get_mut(..length).ok_or_else(|| { + Error::Invalid("restored image is shorter than its mapping".to_owned()) + })?; + edit(image) + } + + fn finalize( + &mut self, + source: &[u8], + layout: &ElfLayout, + data_start: u64, + preserve_entrypoint: bool, + ) -> Result { + // Everything appended below fits in this bound, which the caller has + // already held to the output ceiling. Reserving it here means the + // appends cannot grow the buffer, so a failed allocation is reported + // instead of aborting. + let tail = usize_from_u64(appended_tail_bound(layout), "retained section tail")?; + self.reserve(tail)?; + let mut stream = std::io::Cursor::new(&mut self.bytes); + finalize_clean_elf( + &mut stream, + Self::label(), + source, + layout, + data_start, + preserve_entrypoint, + |_| Ok(()), + ) + } + + fn view(&mut self, read: impl FnOnce(&[u8]) -> Result) -> Result { + read(&self.bytes) + } +} + +/// Upper bound for what [`finalize_clean_elf`] appends: every retained +/// non-loaded section with its alignment padding, plus the header table. +fn appended_tail_bound(layout: &ElfLayout) -> u64 { + let retained = layout + .section_headers + .get(..layout.private_section_index) + .unwrap_or(&[]); + let sections = retained + .iter() + .filter(|section| { + section.section_type != SHT_NOBITS + && section.flags & SHF_ALLOC == 0 + && section.size != 0 + }) + .fold(0_u64, |total, section| { + total + .saturating_add(section.size) + .saturating_add(section.alignment.max(1)) + }); + sections + .saturating_add(8) + .saturating_add(0x40_u64.saturating_mul(retained.len() as u64)) +} + +/// The largest restored image the limits allow: one entry, within the task +/// total. +fn output_ceiling(limits: &ResourceLimits) -> u64 { + limits.max_entry_bytes.min(limits.max_total_bytes) +} + +/// Estimate of the bytes a restoration appends after the private-section +/// offset: the rebuilt dynamic tables and the retained tail. +/// +/// The rebuilt tables hold the input's own tables plus what the auxiliary +/// image contributes, so the input table sizes and a multiple of the auxiliary +/// size cover them. This sizes one reservation and nothing else; a low +/// estimate costs a reallocation, never correctness. +fn appended_reserve_hint(source: &[u8], layout: &ElfLayout, auxiliary_size: u32) -> u64 { + const TABLES: [&str; 8] = [ + ".dynsym", + ".gnu.version", + ".gnu.version_r", + ".gnu.hash", + ".hash", + ".dynstr", + ".rela.dyn", + ".rela.plt", + ]; + let Ok(names) = layout.section_names(source) else { + return 0; + }; + let tables = layout + .section_headers + .iter() + .zip(&names) + .filter(|(_, name)| TABLES.contains(&name.as_str())) + .fold(0_u64, |total, (section, _)| { + total.saturating_add(section.size) + }); + let alignment = layout.load_alignment().unwrap_or(0x1_0000); + tables + .saturating_add(u64::from(auxiliary_size).saturating_mul(3)) + .saturating_add(alignment.saturating_mul(2)) + .saturating_add(appended_tail_bound(layout)) +} + +/// The decoded stage-2 inputs one restoration reads. +struct RestoreInputs<'a> { + /// The protected ELF. + source: &'a [u8], + /// The `0x9D` payload: descriptor, primary and auxiliary containers. + payload: &'a [u8], + config: &'a Module9bConfig, + symbol_patch_data: &'a [u8], + auxiliary_symbol_seed: Option, + constructor_module: Option<(&'a [u8], u32)>, +} + +struct RestoreFlags<'a> { + dump_auxiliary: Option<&'a Path>, + outer_only: bool, + preserve_entrypoint: bool, + verbose: bool, +} + +/// What a restoration observed, apart from where its bytes went. +struct RestoreParts { + descriptor: DescriptorReport, + primary: DecodeStatistics, + auxiliary: Option, + materialization: Option, + cleaning: CleaningReport, + validation: ValidationReport, +} + +fn static_config_report(config: &Module9bConfig) -> StaticConfigReport { + StaticConfigReport { + header_seed: format!("0x{:08X}", config.header_seed), + container_seed: format!("0x{:08X}", config.container_seed), + aes_key_sha256: sha256_bytes(&config.aes_key), + schedule_offset: format!("0x{:X}", config.schedule_offset), + } +} + +/// Charge one stage-2 image the restoration retains, on the same rule as an +/// artifact read from disk. +fn charge_artifact(data: &[u8], limits: &ResourceLimits, bytes: &mut ByteBudget) -> Result<()> { + let length = u64::try_from(data.len()) + .map_err(|_| Error::Invalid("artifact length exceeds u64".to_owned()))?; + limits.check_entry_bytes(length)?; + bytes.charge(length)?; + Ok(()) +} + +/// Rebuild the static image from `inputs` into `output`. +fn restore_image( + inputs: &RestoreInputs<'_>, + flags: &RestoreFlags<'_>, + limits: &ResourceLimits, + bytes: &mut ByteBudget, + records: &mut EntryBudget, + output: &mut O, +) -> Result { + let RestoreInputs { + source, + payload, + config, + symbol_patch_data, + auxiliary_symbol_seed, + constructor_module, + } = *inputs; + let layout = ElfLayout::parse(source, true)?; + let private = layout.private_section()?; + let file_load_end = layout.file_load_end()?; + let aligned_load_end = align_up(file_load_end, 0x10)?; + if private.offset != aligned_load_end { + return invalid(format!( + "SHT_LOUSER offset 0x{:x} != aligned file-backed PT_LOAD end 0x{aligned_load_end:x} (raw 0x{file_load_end:x})", + private.offset + )); + } + let load_padding = slice_u64(source, file_load_end, private.offset - file_load_end)?; + if load_padding.iter().any(|&byte| byte != 0) { + return invalid(format!( + "nonzero padding between PT_LOAD end 0x{file_load_end:x} and SHT_LOUSER 0x{:x}", + private.offset + )); + } + let descriptor = ProtectedDescriptor::decrypt(payload, config.header_seed)?; + let load_end = layout.load_end()?; + if u64::from(descriptor.outer_expected_size) != load_end { + return invalid(format!( + "0x9D target size 0x{:x} != ELF load size 0x{load_end:x}", + descriptor.outer_expected_size + )); + } + let outer = ContainerHeader::parse( + payload, + descriptor.outer_offset as usize, + config.container_seed, + )?; + if u64::from(outer.output_size) != load_end { + return invalid(format!( + "primary container output 0x{:x} != ELF load size 0x{load_end:x}", + outer.output_size + )); + } + let auxiliary_header = ContainerHeader::parse( + payload, + descriptor.auxiliary_offset as usize, + config.container_seed, + )?; + if auxiliary_header.output_size != descriptor.auxiliary_expected_size { + return invalid("auxiliary container output size does not match the 0x9D descriptor"); + } + // The auxiliary image is one flat allocation. Reject its declared size + // before that buffer is reserved, even when outer-only mode will not + // decode it: a hostile size must not depend on a later branch to be safe. + // The same check repeats inside `allocate_auxiliary`, which is also what + // charges the buffer; this one only guards the outer-only path. + limits.check_entry_bytes(u64::from(auxiliary_header.output_size))?; + if outer.encoded_end()? != descriptor.auxiliary_offset as usize { + return invalid("primary and auxiliary 0x9D containers are not contiguous"); + } + + let private_size = usize_from_u64(private.offset, "private section offset")?; + // The output is one image. It is capped by the smaller of the + // single-entry ceiling and the task total, but it is not added to the + // decoder byte budget: that budget counts retained decoded bytes, and the + // output is the image those bytes are written into. + limits.check_entry_bytes(private.offset.min(limits.max_total_bytes))?; + if private.offset > limits.max_total_bytes { + return Err(crate::android::LimitExceeded::Total { + requested: private.offset, + adding: private.offset, + limit: limits.max_total_bytes, + } + .into()); + } + let prefix = source + .get(..private_size) + .ok_or_else(|| Error::Invalid("private section offset is outside the input".to_owned()))?; + let reserve = if flags.outer_only { + appended_tail_bound(&layout) + } else { + appended_reserve_hint(source, &layout, auxiliary_header.output_size) + }; + // The hint is computed from section sizes the input declares. Whatever it + // says, the reservation stays inside the ceiling the image itself is held + // to, so a hostile size cannot turn into a large allocation here. + let reserve = reserve.min(output_ceiling(limits).saturating_sub(private.offset)); + output.start(prefix, reserve)?; + output.set_len(private.offset, "size temporary output")?; + + let mut restored_layout = layout.clone(); + let mut auxiliary_stats = None; + let mut materialization = None; + let mut temporary_end = private.offset; + let primary_stats = output.edit(private_size, |image| { + if flags.verbose { + crate::progress::stage(Step::AndroidPrimary); + } + let mut writer = FileLayoutWriter { + output: image, + layout: &layout, + load_end, + }; + let mut context = DecodeContext { + limits, + bytes: &mut *bytes, + records: &mut *records, + validate: |address: u64, length: usize| { + let data_len = u64::try_from(length) + .map_err(|_| Error::Invalid("decoded write length exceeds u64".to_owned()))?; + let end = address + .checked_add(data_len) + .ok_or_else(|| Error::Invalid("decoded write range overflow".to_owned()))?; + if end > load_end { + return invalid(format!( + "decoded write 0x{address:x}..0x{end:x} exceeds target load image" + )); + } + Ok(()) + }, + }; + decode_container( + payload, + &outer, + config, + flags.verbose, + &mut context, + |address, data| writer.write(address, data), + ) + })?; + + if !flags.outer_only { + if flags.verbose { + crate::progress::stage(Step::AndroidAuxiliary); + } + let mut decoded = allocate_auxiliary(auxiliary_header.output_size, limits, bytes)?; + let auxiliary_len = decoded.len(); + let mut context = DecodeContext { + limits, + bytes: &mut *bytes, + records: &mut *records, + validate: |offset: u64, length: usize| { + let start = usize_from_u64(offset, "auxiliary write offset")?; + let end = start + .checked_add(length) + .ok_or_else(|| Error::Invalid("auxiliary decoded write overflow".to_owned()))?; + if end > auxiliary_len { + return invalid("auxiliary decoded write is out of range".to_owned()); + } + Ok(()) + }, + }; + let stats = decode_container( + payload, + &auxiliary_header, + config, + flags.verbose, + &mut context, + |offset, data| { + let start = usize_from_u64(offset, "auxiliary write offset")?; + let end = start + .checked_add(data.len()) + .ok_or_else(|| Error::Invalid("auxiliary decoded write overflow".to_owned()))?; + let destination = decoded.get_mut(start..end).ok_or_else(|| { + Error::Invalid("auxiliary decoded write is out of range".to_owned()) + })?; + destination.copy_from_slice(data); + Ok(data.len()) + }, + )?; + if let Some(path) = flags.dump_auxiliary { + write_atomic(&absolute(path)?, &decoded)?; + } + let mapping_length = metadata_mapping_length(source, &layout, &decoded)?; + if mapping_length < private_size { + return invalid("dynamic-table mapping is shorter than the ELF image"); + } + let mapping_bytes = u64::try_from(mapping_length) + .map_err(|_| Error::Invalid("dynamic-table mapping length exceeds u64".to_owned()))?; + limits.check_entry_bytes(mapping_bytes.min(limits.max_total_bytes))?; + if mapping_bytes > limits.max_total_bytes { + return Err(crate::android::LimitExceeded::Total { + requested: mapping_bytes, + adding: mapping_bytes, + limit: limits.max_total_bytes, + } + .into()); + } + output.set_len(mapping_bytes, "extend temporary output")?; + if flags.verbose { + crate::progress::stage(Step::AndroidTables); + } + let (new_layout, report, data_end) = output.edit(mapping_length, |image| { + materialize_static_elf_tables( + image, + source, + &layout, + symbol_patch_data, + &decoded, + MaterializeInput { + auxiliary_symbol_seed, + constructor_module, + limits, + }, + ) + })?; + restored_layout = new_layout; + materialization = Some(report); + auxiliary_stats = Some(stats); + temporary_end = data_end; + output.set_len(temporary_end, "trim temporary output")?; + } + + // The retained sections are slices of the input, and a section table may + // declare them overlapping. Their sum is bounded before any is appended. + let finished_bound = temporary_end.saturating_add(appended_tail_bound(&restored_layout)); + limits.check_entry_bytes(finished_bound.min(limits.max_total_bytes))?; + if finished_bound > limits.max_total_bytes { + return Err(crate::android::LimitExceeded::Total { + requested: finished_bound, + adding: finished_bound, + limit: limits.max_total_bytes, + } + .into()); + } + let cleaning = output.finalize( + source, + &restored_layout, + temporary_end, + flags.preserve_entrypoint, + )?; + let validation = output.view(|restored| { + validate_restored_binary( + restored, + flags.preserve_entrypoint, + materialization.as_ref(), + ) + })?; + + Ok(RestoreParts { + descriptor: DescriptorReport { + command_id: format!("0x{:X}", descriptor.command_id), + flags: format!("0x{:X}", descriptor.flags), + outer_offset: format!("0x{:X}", descriptor.outer_offset), + outer_expected_size: format!("0x{:X}", descriptor.outer_expected_size), + auxiliary_offset: format!("0x{:X}", descriptor.auxiliary_offset), + auxiliary_expected_size: format!("0x{:X}", descriptor.auxiliary_expected_size), + }, + primary: primary_stats, + auxiliary: auxiliary_stats, + materialization, + cleaning, + validation, + }) +} + /// Restore the current protected `libil2cpp.so` without executing protector code. pub fn restore_libil2cpp(options: &RestoreOptions) -> Result { restore_libil2cpp_with_limits(options, &ResourceLimits::default()) @@ -2542,7 +3125,7 @@ pub fn restore_libil2cpp_with_limits( } let artifacts = load_artifacts(&index_path)?; let mut bytes = ByteBudget::new(limits); - let mut records = crate::android::EntryBudget::new(limits); + let mut records = EntryBudget::new(limits); let module = read_artifact(&artifacts[&0x9b].path, limits, &mut bytes)?; let symbol_patch_data = read_artifact(&artifacts[&0x9e].path, limits, &mut bytes)?; let auxiliary_symbol_seed = artifacts @@ -2555,14 +3138,7 @@ pub fn restore_libil2cpp_with_limits( let constructor_module = artifacts .get(&0x98) .map(|artifact| -> Result<_> { - let entry = artifact - .entry_offset - .filter(|entry| *entry != 0) - .ok_or_else(|| { - Error::Invalid( - "constructor module 0x98 lacks its descriptor entry offset".to_owned(), - ) - })?; + let entry = constructor_entry(artifact.entry_offset)?; Ok((read_artifact(&artifact.path, limits, &mut bytes)?, entry)) }) .transpose()?; @@ -2575,254 +3151,37 @@ pub fn restore_libil2cpp_with_limits( let payload_file = File::open(payload_path) .map_err(|error| Error::io("open 0x9D artifact", payload_path, error))?; let payload = map_read_only(&payload_file, payload_path)?; - let layout = ElfLayout::parse(&source, true)?; - let private = layout.private_section()?; - let file_load_end = layout.file_load_end()?; - let aligned_load_end = align_up(file_load_end, 0x10)?; - if private.offset != aligned_load_end { - return invalid(format!( - "SHT_LOUSER offset 0x{:x} != aligned file-backed PT_LOAD end 0x{aligned_load_end:x} (raw 0x{file_load_end:x})", - private.offset - )); - } - let load_padding = slice_u64(&source, file_load_end, private.offset - file_load_end)?; - if load_padding.iter().any(|&byte| byte != 0) { - return invalid(format!( - "nonzero padding between PT_LOAD end 0x{file_load_end:x} and SHT_LOUSER 0x{:x}", - private.offset - )); - } - let descriptor = ProtectedDescriptor::decrypt(&payload, config.header_seed)?; - let load_end = layout.load_end()?; - if u64::from(descriptor.outer_expected_size) != load_end { - return invalid(format!( - "0x9D target size 0x{:x} != ELF load size 0x{load_end:x}", - descriptor.outer_expected_size - )); - } - let outer = ContainerHeader::parse( - &payload, - descriptor.outer_offset as usize, - config.container_seed, - )?; - if u64::from(outer.output_size) != load_end { - return invalid(format!( - "primary container output 0x{:x} != ELF load size 0x{load_end:x}", - outer.output_size - )); - } - let auxiliary_header = ContainerHeader::parse( - &payload, - descriptor.auxiliary_offset as usize, - config.container_seed, - )?; - if auxiliary_header.output_size != descriptor.auxiliary_expected_size { - return invalid("auxiliary container output size does not match the 0x9D descriptor"); - } - // The auxiliary image is one flat allocation. Reject its declared size - // before that buffer is reserved, even when outer-only mode will not - // decode it: a hostile size must not depend on a later branch to be safe. - // The same check repeats inside `allocate_auxiliary`, which is also what - // charges the buffer; this one only guards the outer-only path. - limits.check_entry_bytes(u64::from(auxiliary_header.output_size))?; - if outer.encoded_end()? != descriptor.auxiliary_offset as usize { - return invalid("primary and auxiliary 0x9D containers are not contiguous"); - } - let parent = output_path.parent().unwrap_or_else(|| Path::new(".")); - std::fs::create_dir_all(parent) - .map_err(|error| Error::io("create output directory", parent, error))?; - let mut temporary = NamedTempFile::new_in(parent) - .map_err(|error| Error::io("create temporary output", parent, error))?; - let temporary_path = temporary.path().to_path_buf(); - let private_size = usize_from_u64(private.offset, "private section offset")?; - // The temporary output is one file. It is capped by the smaller of the - // single-entry ceiling and the task total, but it is not added to the - // decoder byte budget: that budget counts retained decoded bytes, and the - // output file is the image those bytes are written into. - limits.check_entry_bytes(private.offset.min(limits.max_total_bytes))?; - if private.offset > limits.max_total_bytes { - return Err(crate::android::LimitExceeded::Total { - requested: private.offset, - adding: private.offset, - limit: limits.max_total_bytes, - } - .into()); - } - copy_range( - &source, - temporary.as_file_mut(), - private_size, - &temporary_path, - )?; - temporary - .as_file_mut() - .flush() - .map_err(|error| Error::io("flush initial output", &temporary_path, error))?; - temporary - .as_file() - .set_len(private.offset) - .map_err(|error| Error::io("size temporary output", &temporary_path, error))?; - - let mut restored_layout = layout.clone(); - let mut auxiliary_stats = None; - let mut materialization = None; - let mut temporary_end = private.offset; - let primary_stats; - { - let mut output = map_mut(temporary.as_file(), private_size, &temporary_path)?; - if options.verbose { - crate::progress::stage(Step::AndroidPrimary); - } - let mut writer = FileLayoutWriter { - output: &mut output, - layout: &layout, - load_end, - }; - let mut context = DecodeContext { - limits, - bytes: &mut bytes, - records: &mut records, - validate: |address: u64, length: usize| { - let data_len = u64::try_from(length) - .map_err(|_| Error::Invalid("decoded write length exceeds u64".to_owned()))?; - let end = address - .checked_add(data_len) - .ok_or_else(|| Error::Invalid("decoded write range overflow".to_owned()))?; - if end > load_end { - return invalid(format!( - "decoded write 0x{address:x}..0x{end:x} exceeds target load image" - )); - } - Ok(()) - }, - }; - primary_stats = decode_container( - &payload, - &outer, - &config, - options.verbose, - &mut context, - |address, data| writer.write(address, data), - )?; - output - .flush() - .map_err(|error| Error::io("flush restored image", &temporary_path, error))?; - } - - if !options.outer_only { - if options.verbose { - crate::progress::stage(Step::AndroidAuxiliary); - } - let mut decoded = allocate_auxiliary(auxiliary_header.output_size, limits, &mut bytes)?; - let auxiliary_len = decoded.len(); - let mut context = DecodeContext { - limits, - bytes: &mut bytes, - records: &mut records, - validate: |offset: u64, length: usize| { - let start = usize_from_u64(offset, "auxiliary write offset")?; - let end = start - .checked_add(length) - .ok_or_else(|| Error::Invalid("auxiliary decoded write overflow".to_owned()))?; - if end > auxiliary_len { - return invalid("auxiliary decoded write is out of range".to_owned()); - } - Ok(()) - }, - }; - let stats = decode_container( - &payload, - &auxiliary_header, - &config, - options.verbose, - &mut context, - |offset, data| { - let start = usize_from_u64(offset, "auxiliary write offset")?; - let end = start - .checked_add(data.len()) - .ok_or_else(|| Error::Invalid("auxiliary decoded write overflow".to_owned()))?; - let destination = decoded.get_mut(start..end).ok_or_else(|| { - Error::Invalid("auxiliary decoded write is out of range".to_owned()) - })?; - destination.copy_from_slice(data); - Ok(data.len()) - }, - )?; - if let Some(path) = &options.dump_auxiliary { - write_atomic(&absolute(path)?, &decoded)?; - } - let mapping_length = metadata_mapping_length(&source, &layout, &decoded)?; - if mapping_length < private_size { - return invalid("dynamic-table mapping is shorter than the ELF image"); - } - let mapping_bytes = u64::try_from(mapping_length) - .map_err(|_| Error::Invalid("dynamic-table mapping length exceeds u64".to_owned()))?; - limits.check_entry_bytes(mapping_bytes.min(limits.max_total_bytes))?; - if mapping_bytes > limits.max_total_bytes { - return Err(crate::android::LimitExceeded::Total { - requested: mapping_bytes, - adding: mapping_bytes, - limit: limits.max_total_bytes, - } - .into()); - } - temporary - .as_file() - .set_len(mapping_bytes) - .map_err(|error| Error::io("extend temporary output", &temporary_path, error))?; - if options.verbose { - crate::progress::stage(Step::AndroidTables); - } - { - let mut output = map_mut(temporary.as_file(), mapping_length, &temporary_path)?; - let (new_layout, report, data_end) = materialize_static_elf_tables( - &mut output, - &source, - &layout, - &symbol_patch_data, - &decoded, - MaterializeInput { - auxiliary_symbol_seed, - constructor_module: constructor_module - .as_ref() - .map(|(image, entry)| (image.as_slice(), *entry)), - limits, - }, - )?; - restored_layout = new_layout; - materialization = Some(report); - auxiliary_stats = Some(stats); - temporary_end = data_end; - output - .flush() - .map_err(|error| Error::io("flush restored image", &temporary_path, error))?; - } - temporary - .as_file() - .set_len(temporary_end) - .map_err(|error| Error::io("trim temporary output", &temporary_path, error))?; - } - - let cleaning = finalize_clean_elf( - temporary.as_file_mut(), - &temporary_path, - &source, - &restored_layout, - temporary_end, - options.preserve_entrypoint, - )?; - let validation = { - let restored = map_read_only(temporary.as_file(), &temporary_path)?; - validate_restored_binary( - &restored, - options.preserve_entrypoint, - materialization.as_ref(), - )? + let mut output = DiskOutput { + parent: output_path + .parent() + .unwrap_or_else(|| Path::new(".")) + .to_path_buf(), + temporary: None, }; - temporary - .persist(&output_path) - .map_err(|error| Error::io("replace restored output", &output_path, error.error))?; + let parts = restore_image( + &RestoreInputs { + source: &source, + payload: &payload, + config: &config, + symbol_patch_data: &symbol_patch_data, + auxiliary_symbol_seed, + constructor_module: constructor_module + .as_ref() + .map(|(image, entry)| (image.as_slice(), *entry)), + }, + &RestoreFlags { + dump_auxiliary: options.dump_auxiliary.as_deref(), + outer_only: options.outer_only, + preserve_entrypoint: options.preserve_entrypoint, + verbose: options.verbose, + }, + limits, + &mut bytes, + &mut records, + &mut output, + )?; + output.persist(&output_path)?; Ok(RestoreReport { input: input_path.display().to_string(), @@ -2833,32 +3192,143 @@ pub fn restore_libil2cpp_with_limits( .map_err(|error| Error::io("inspect restored output", &output_path, error))? .len(), module_index: index_path.display().to_string(), - static_config: StaticConfigReport { - header_seed: format!("0x{:08X}", config.header_seed), - container_seed: format!("0x{:08X}", config.container_seed), - aes_key_sha256: sha256_bytes(&config.aes_key), - schedule_offset: format!("0x{:X}", config.schedule_offset), - }, - descriptor: DescriptorReport { - command_id: format!("0x{:X}", descriptor.command_id), - flags: format!("0x{:X}", descriptor.flags), - outer_offset: format!("0x{:X}", descriptor.outer_offset), - outer_expected_size: format!("0x{:X}", descriptor.outer_expected_size), - auxiliary_offset: format!("0x{:X}", descriptor.auxiliary_offset), - auxiliary_expected_size: format!("0x{:X}", descriptor.auxiliary_expected_size), - }, - primary: primary_stats, - auxiliary: auxiliary_stats, - elf_materialization: materialization, - cleaning, - validation, + static_config: static_config_report(&config), + descriptor: parts.descriptor, + primary: parts.primary, + auxiliary: parts.auxiliary, + elf_materialization: parts.materialization, + cleaning: parts.cleaning, + validation: parts.validation, elapsed_seconds: started.elapsed().as_secs_f64(), }) } + +fn constructor_entry(entry_offset: Option) -> Result { + entry_offset.filter(|entry| *entry != 0).ok_or_else(|| { + Error::Invalid("constructor module 0x98 lacks its descriptor entry offset".to_owned()) + }) +} + +/// A restored image held in memory, with what the restoration observed. +/// +/// The fields other than `bytes` are the ones [`RestoreReport`] carries for an +/// on-disk restore. Paths, file digests and the elapsed time are left to the +/// caller, which is the one that knows where the bytes came from. +#[derive(Debug, Clone, PartialEq)] +pub struct RestoredImage { + pub bytes: Vec, + pub static_config: StaticConfigReport, + pub descriptor: DescriptorReport, + pub primary: DecodeStatistics, + pub auxiliary: Option, + pub elf_materialization: Option, + pub cleaning: CleaningReport, + pub validation: ValidationReport, +} + +/// [`restore_libil2cpp_with_limits`] over bytes, writing nothing. +/// +/// `input` is the protected ELF and `extraction` its in-memory Stage 2 +/// extraction. The restored bytes are identical to the file the on-disk driver +/// writes for the same input: both run the same restoration, and differ only in +/// where the image is held while it is built. +pub fn restore_libil2cpp_in_memory( + input: &[u8], + extraction: &MemoryExtraction, + verbose: bool, + limits: &ResourceLimits, +) -> Result { + let artifacts = memory_artifacts(extraction, input)?; + let mut bytes = ByteBudget::new(limits); + let mut records = EntryBudget::new(limits); + let module = artifacts[&0x9b].data; + charge_artifact(module, limits, &mut bytes)?; + let symbol_patch_data = artifacts[&0x9e].data; + charge_artifact(symbol_patch_data, limits, &mut bytes)?; + let auxiliary_symbol_seed = artifacts + .get(&0x96) + .map(|artifact| -> Result<_> { + charge_artifact(artifact.data, limits, &mut bytes)?; + discover_auxiliary_symbol_seed(artifact.data) + }) + .transpose()?; + let constructor_module = artifacts + .get(&0x98) + .map(|artifact| -> Result<_> { + let entry = constructor_entry(artifact.entry_offset)?; + charge_artifact(artifact.data, limits, &mut bytes)?; + Ok((artifact.data, entry)) + }) + .transpose()?; + let config = Module9bConfig::parse(module)?; + + let mut output = MemoryOutput::default(); + let parts = restore_image( + &RestoreInputs { + source: input, + payload: artifacts[&0x9d].data, + config: &config, + symbol_patch_data, + auxiliary_symbol_seed, + constructor_module, + }, + &RestoreFlags { + dump_auxiliary: None, + outer_only: false, + preserve_entrypoint: false, + verbose, + }, + limits, + &mut bytes, + &mut records, + &mut output, + )?; + Ok(RestoredImage { + bytes: output.bytes, + static_config: static_config_report(&config), + descriptor: parts.descriptor, + primary: parts.primary, + auxiliary: parts.auxiliary, + elf_materialization: parts.materialization, + cleaning: parts.cleaning, + validation: parts.validation, + }) +} #[cfg(test)] mod tests { use super::*; + #[test] + fn a_reserve_hint_that_cannot_be_met_does_not_fail_the_image() { + let mut output = MemoryOutput::default(); + output + .start(b"prefix", u64::MAX) + .expect("the hint is only a hint"); + assert_eq!(output.bytes, b"prefix"); + } + + #[test] + fn a_memory_image_grows_with_zeroes_truncates_and_bounds_its_edits() { + let mut output = MemoryOutput::default(); + output.start(&[1, 2, 3], 0).unwrap(); + output.set_len(5, "grow").unwrap(); + assert_eq!(output.bytes, [1, 2, 3, 0, 0]); + output + .edit(5, |image| { + image[4] = 9; + Ok(()) + }) + .unwrap(); + output.set_len(2, "truncate").unwrap(); + assert_eq!(output.bytes, [1, 2]); + let error = output + .edit(3, |_| Ok(())) + .expect_err("an edit past the image is refused"); + assert!(error.to_string().contains("shorter"), "{error}"); + let seen = output.view(|image| Ok(image.to_vec())).unwrap(); + assert_eq!(seen, [1, 2]); + } + /// `decode_container` rejects a writer whose declared length fits the entry /// ceiling but whose target ends past the destination. The writer closure /// counts calls and must stay at zero. diff --git a/senbei-gui/src/ui/dialogs.rs b/senbei-gui/src/ui/dialogs.rs index fb9997e..1f3fc1e 100644 --- a/senbei-gui/src/ui/dialogs.rs +++ b/senbei-gui/src/ui/dialogs.rs @@ -465,6 +465,82 @@ pub struct Overlays<'a> { pub detected: Lang, } +#[derive(Clone, Copy, PartialEq, Eq)] +enum Dialog { + Settings, + Legal { reviewing: bool }, +} + +impl Dialog { + fn requested(view: &ViewState, legal_pending: bool) -> Option { + if legal_pending || view.legal_open { + Some(Self::Legal { + reviewing: !legal_pending, + }) + } else { + view.settings_open.then_some(Self::Settings) + } + } +} + +struct VisibleDialog { + kind: Dialog, + opacity: f32, + active: bool, +} + +impl VisibleDialog { + /// Keep the outgoing dialog modal until transparent. A replacement starts + /// only then, so two backdrops never darken the workbench at once. + fn animate(ctx: &Context, requested: Option) -> Option { + let slot = Id::unique("workbench-dialog"); + let fade = slot.with("opacity"); + let duration = ctx.global_style().animation_time; + let mut kind = match ctx.data(|data| data.get_temp::(slot)) { + Some(shown) => shown, + None => { + let next = requested?; + ctx.animate_value_with_time(fade, 0.0, 0.0); + next + } + }; + let mut active = requested == Some(kind); + let mut opacity = + ctx.animate_value_with_time(fade, if active { 1.0 } else { 0.0 }, duration); + if !active && opacity == 0.0 { + ctx.data_mut(|data| data.remove::(slot)); + kind = requested?; + active = true; + opacity = ctx.animate_value_with_time(fade, 1.0, duration); + } + ctx.data_mut(|data| data.insert_temp(slot, kind)); + Some(Self { + kind, + opacity, + active, + }) + } + + fn show(self, ctx: &Context, content: impl FnOnce(&mut Ui)) -> egui::ModalResponse<()> { + let id = Id::unique(match self.kind { + Dialog::Settings => "settings", + Dialog::Legal { .. } => "legal", + }); + Modal::new(id) + .area(Modal::default_area(id).fade_in(false)) + .frame(modal_frame().multiply_with_opacity(self.opacity)) + .backdrop_color(theme::backdrop().gamma_multiply(self.opacity)) + .show(ctx, |ui| { + if !self.active { + ui.disable(); + } + // Disable input on exit without applying the disabled fade twice. + ui.set_opacity(self.opacity); + content(ui); + }) + } +} + pub fn overlays( ctx: &Context, draw: &mut Draw<'_>, @@ -472,17 +548,27 @@ pub fn overlays( settings: &mut Settings, overlays: Overlays<'_>, ) { - if ctx.input(|input| !input.raw.hovered_files.is_empty()) { + let requested = Dialog::requested(view, overlays.legal_pending); + let shown = VisibleDialog::animate(ctx, requested); + if shown.is_none() && ctx.input(|input| !input.raw.hovered_files.is_empty()) { drop_overlay(ctx); } - if view.settings_open { - settings_modal(ctx, draw, view, settings, &overlays); - } + let legal = match shown { + Some(dialog) if dialog.kind == Dialog::Settings => { + settings_modal(ctx, dialog, draw, view, settings, &overlays); + None + } + other => other, + }; if view.close_confirm { close_modal(ctx, draw, view); } - if overlays.legal_pending || view.legal_open { - legal_modal(ctx, draw, view, settings, &overlays); + if let Some(dialog) = legal { + legal_modal(ctx, dialog, draw, view, settings, &overlays); + } + // A button can change the requested dialog after this frame's animation. + if Dialog::requested(view, !settings.legal_accepted) != requested { + ctx.request_repaint(); } } @@ -543,73 +629,74 @@ fn language_combo(ui: &mut Ui, id: &str, settings: &mut Settings, detected: Lang fn legal_modal( ctx: &Context, + dialog: VisibleDialog, draw: &mut Draw<'_>, view: &mut ViewState, settings: &mut Settings, overlays: &Overlays<'_>, ) { - Modal::new(Id::unique("legal")) - .frame(modal_frame()) - .backdrop_color(theme::backdrop()) - .show(ctx, |ui| { - ui.set_width(620.0_f32.min(ctx.content_rect().width() - 40.0)); - ui.spacing_mut().item_spacing.y = 0.0; - modal_section(ui, Margin::symmetric(16, 12), |ui| { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 10.0; - if let Some(image) = icon_image(overlays.icon, 24.0) { - ui.add(image); - } - ui.label(RichText::new(t(Text::LegalTitle)).font(theme::title(17.0))); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - language_combo(ui, "legal-language", settings, overlays.detected); - }); + let reviewing = matches!(dialog.kind, Dialog::Legal { reviewing: true }); + dialog.show(ctx, |ui| { + ui.set_width(620.0_f32.min(ctx.content_rect().width() - 40.0)); + ui.spacing_mut().item_spacing.y = 0.0; + modal_section(ui, Margin::symmetric(16, 12), |ui| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 10.0; + if let Some(image) = icon_image(overlays.icon, 24.0) { + ui.add(image); + } + ui.label(RichText::new(t(Text::LegalTitle)).font(theme::title(17.0))); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + language_combo(ui, "legal-language", settings, overlays.detected); }); }); - widgets::rule(ui); - modal_section(ui, Margin::symmetric(16, 14), |ui| { - ui.spacing_mut().item_spacing.y = 10.0; - for text in [Text::LegalP1, Text::LegalP2, Text::LegalP3, Text::LegalP4] { - let text = t(text); - let mut job = LayoutJob::default(); - for (strong, run) in strong_runs(&text) { - job.append( - run, - 0.0, - TextFormat { - font_id: if strong { - theme::strong(13.5) - } else { - theme::body() - }, - color: if strong { theme::TEXT } else { theme::DIM }, - ..Default::default() + }); + widgets::rule(ui); + modal_section(ui, Margin::symmetric(16, 14), |ui| { + ui.spacing_mut().item_spacing.y = 10.0; + for text in [Text::LegalP1, Text::LegalP2, Text::LegalP3, Text::LegalP4] { + let text = t(text); + let mut job = LayoutJob::default(); + for (strong, run) in strong_runs(&text) { + job.append( + run, + 0.0, + TextFormat { + font_id: if strong { + theme::strong(13.5) + } else { + theme::body() }, - ); - } - job.wrap.max_width = ui.available_width(); - ui.add(egui::Label::new(job).wrap()); + color: if strong { theme::TEXT } else { theme::DIM }, + ..Default::default() + }, + ); } - }); - widgets::rule(ui); - modal_section(ui, Margin::symmetric(16, 10), |ui| { - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.spacing_mut().item_spacing.x = 8.0; + job.wrap.max_width = ui.available_width(); + ui.add(egui::Label::new(job).wrap()); + } + }); + widgets::rule(ui); + modal_section(ui, Margin::symmetric(16, 10), |ui| { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = 8.0; + if reviewing { + if widgets::primary_button(ui, t(Text::SettingsDone), true).clicked() { + view.legal_open = false; + } + } else { if widgets::primary_button(ui, t(Text::LegalAccept), true).clicked() { draw.act(Action::AcceptLegal); settings.legal_accepted = true; view.legal_open = false; } if ui.button(t(Text::LegalQuit)).clicked() { - if overlays.legal_pending { - draw.act(Action::Quit); - } else { - view.legal_open = false; - } + draw.act(Action::Quit); } - }); + } }); }); + }); } fn close_modal(ctx: &Context, draw: &mut Draw<'_>, view: &mut ViewState) { @@ -691,79 +778,74 @@ fn mib(ui: &mut Ui, value: &mut u64) -> Response { fn settings_modal( ctx: &Context, + dialog: VisibleDialog, draw: &mut Draw<'_>, view: &mut ViewState, settings: &mut Settings, overlays: &Overlays<'_>, ) { - let response = Modal::new(Id::unique("settings")) - .frame(modal_frame()) - .backdrop_color(theme::backdrop()) - .show(ctx, |ui| { - ui.set_width(760.0_f32.min(ctx.content_rect().width() - 40.0)); - ui.spacing_mut().item_spacing.y = 0.0; - modal_section(ui, Margin::symmetric(16, 12), |ui| { - ui.horizontal(|ui| { - ui.label(RichText::new(t(Text::SettingsTitle)).font(theme::title(17.0))); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - if widgets::ghost_button(ui, "✕").clicked() { - view.settings_open = false; - } - }); - }); - }); - widgets::rule(ui); - ui.horizontal_top(|ui| { - ui.spacing_mut().item_spacing.x = 0.0; - ui.allocate_ui_with_layout( - vec2(160.0, 380.0), - Layout::top_down(Align::Min), - |ui| { - ui.set_min_size(vec2(160.0, 380.0)); - modal_section(ui, Margin::symmetric(6, 8), |ui| { - ui.spacing_mut().item_spacing.y = 2.0; - for (tab, text) in [ - (SettingsTab::General, Text::SettingsTabGeneral), - (SettingsTab::Processing, Text::SettingsTabProcessing), - (SettingsTab::Android, Text::SettingsTabAndroid), - (SettingsTab::Memory, Text::SettingsTabMemory), - (SettingsTab::About, Text::SettingsTabAbout), - ] { - if nav_item(ui, &t(text), view.settings_tab == tab) { - view.settings_tab = tab; - } - } - }); - }, - ); - let line = ui.available_rect_before_wrap(); - ui.painter().vline( - line.left(), - line.top()..=line.top() + 380.0, - Stroke::new(1.0, theme::BORDER), - ); - ui.vertical(|ui| { - modal_section(ui, Margin::symmetric(16, 12), |ui| { - ui.spacing_mut().item_spacing.y = 12.0; - settings_pane(ui, draw, view, settings, overlays); - }); - }); - }); - widgets::rule(ui); - modal_section(ui, Margin::symmetric(16, 10), |ui| { - ui.horizontal(|ui| { - if widgets::ghost_button(ui, t(Text::SettingsReset)).clicked() { - settings.reset(); + let active = dialog.active; + let response = dialog.show(ctx, |ui| { + ui.set_width(760.0_f32.min(ctx.content_rect().width() - 40.0)); + ui.spacing_mut().item_spacing.y = 0.0; + modal_section(ui, Margin::symmetric(16, 12), |ui| { + ui.horizontal(|ui| { + ui.label(RichText::new(t(Text::SettingsTitle)).font(theme::title(17.0))); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if widgets::ghost_button(ui, "✕").clicked() { + view.settings_open = false; } - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - if widgets::primary_button(ui, t(Text::SettingsDone), true).clicked() { - view.settings_open = false; - } - }); }); }); }); - if response.should_close() { + widgets::rule(ui); + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + ui.allocate_ui_with_layout(vec2(160.0, 380.0), Layout::top_down(Align::Min), |ui| { + ui.set_min_size(vec2(160.0, 380.0)); + modal_section(ui, Margin::symmetric(6, 8), |ui| { + ui.spacing_mut().item_spacing.y = 2.0; + for (tab, text) in [ + (SettingsTab::General, Text::SettingsTabGeneral), + (SettingsTab::Processing, Text::SettingsTabProcessing), + (SettingsTab::Android, Text::SettingsTabAndroid), + (SettingsTab::Memory, Text::SettingsTabMemory), + (SettingsTab::About, Text::SettingsTabAbout), + ] { + if nav_item(ui, &t(text), view.settings_tab == tab) { + view.settings_tab = tab; + } + } + }); + }); + let line = ui.available_rect_before_wrap(); + ui.painter().vline( + line.left(), + line.top()..=line.top() + 380.0, + Stroke::new(1.0, theme::BORDER), + ); + ui.vertical(|ui| { + modal_section(ui, Margin::symmetric(16, 12), |ui| { + ui.spacing_mut().item_spacing.y = 12.0; + settings_pane(ui, draw, view, settings, overlays); + }); + }); + }); + widgets::rule(ui); + modal_section(ui, Margin::symmetric(16, 10), |ui| { + ui.horizontal(|ui| { + if widgets::ghost_button(ui, t(Text::SettingsReset)).clicked() { + settings.reset(); + } + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if widgets::primary_button(ui, t(Text::SettingsDone), true).clicked() { + view.settings_open = false; + } + }); + }); + }); + }); + if active && response.should_close() { view.settings_open = false; } } @@ -940,11 +1022,27 @@ fn about(ui: &mut Ui, view: &mut ViewState, overlays: &Overlays<'_>) { if let Some(image) = icon_image(overlays.icon, 72.0) { ui.add(image); } - ui.vertical(|ui| { - ui.label(RichText::new("Senbei").font(theme::title(22.0))); - ui.label(widgets::dim(t(Text::AboutVersion { + let title = + ui.painter() + .layout_no_wrap("Senbei".to_owned(), theme::title(22.0), theme::TEXT); + let version = ui.painter().layout_no_wrap( + t(Text::AboutVersion { v: env!("CARGO_PKG_VERSION").to_owned(), - }))); + }) + .into_owned(), + theme::body(), + theme::DIM, + ); + // Give the row the text block's measured height so it centers the + // block beside the logo rather than starting it at the logo's top. + let size = vec2( + title.size().x.max(version.size().x), + title.size().y + version.size().y, + ); + ui.allocate_ui_with_layout(size, Layout::top_down(Align::Min), |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + ui.label(title); + ui.label(version); }); }); ui.add(egui::Label::new(widgets::dim(t(Text::AboutDesc))).wrap()); @@ -962,3 +1060,63 @@ fn about(ui: &mut Ui, view: &mut ViewState, overlays: &Overlays<'_>) { view.legal_open = true; } } + +#[cfg(test)] +mod tests { + use super::*; + + fn frame(ctx: &Context, time: f64, requested: Option) -> Option { + let mut visible = None; + let input = egui::RawInput { + time: Some(time), + ..Default::default() + }; + let _ = ctx.run_pass(input, |ctx| { + visible = VisibleDialog::animate(ctx, requested) + }); + visible + } + + #[test] + fn startup_legal_fades_both_ways_and_keeps_its_content_on_exit() { + let ctx = Context::default(); + let view = ViewState::default(); + let pending = Dialog::requested(&view, true); + assert!(matches!(pending, Some(Dialog::Legal { reviewing: false }))); + assert_eq!(frame(&ctx, 0.0, pending).unwrap().opacity, 0.0); + assert!((0.0..1.0).contains(&frame(&ctx, 0.1, pending).unwrap().opacity)); + assert_eq!(frame(&ctx, 0.3, pending).unwrap().opacity, 1.0); + + let accepted = Dialog::requested(&view, false); + frame(&ctx, 0.4, accepted).unwrap(); + let outgoing = frame(&ctx, 0.5, accepted).unwrap(); + assert!(Some(outgoing.kind) == pending); + assert!(!outgoing.active); + assert!((0.0..1.0).contains(&outgoing.opacity)); + assert!(frame(&ctx, 0.7, accepted).is_none()); + } + + #[test] + fn opening_legal_from_settings_fades_one_dialog_at_a_time() { + let ctx = Context::default(); + let settings = Some(Dialog::Settings); + let view = ViewState { + legal_open: true, + ..Default::default() + }; + let review = Dialog::requested(&view, false); + assert!(matches!(review, Some(Dialog::Legal { reviewing: true }))); + frame(&ctx, 0.0, settings).unwrap(); + frame(&ctx, 0.3, settings).unwrap(); + frame(&ctx, 0.4, review).unwrap(); + let outgoing = frame(&ctx, 0.5, review).unwrap(); + assert!(outgoing.kind == Dialog::Settings); + assert!(!outgoing.active); + + let incoming = frame(&ctx, 0.7, review).unwrap(); + assert!(Some(incoming.kind) == review); + assert!(incoming.active); + assert_eq!(incoming.opacity, 0.0); + assert_eq!(frame(&ctx, 1.0, review).unwrap().opacity, 1.0); + } +} diff --git a/senbei-gui/src/ui/mod.rs b/senbei-gui/src/ui/mod.rs index c728234..b6d598c 100644 --- a/senbei-gui/src/ui/mod.rs +++ b/senbei-gui/src/ui/mod.rs @@ -563,7 +563,15 @@ impl Workbench { // ------------------------------------------------------------ input + /// Keep workbench-level input out of a modal, including while it fades out. + fn modal_blocks_input(&self, ctx: &Context) -> bool { + !self.settings.legal_accepted || ctx.memory(|memory| memory.top_modal_layer().is_some()) + } + fn take_drops(&mut self, ctx: &Context) { + if self.modal_blocks_input(ctx) { + return; + } let dropped: Vec = ctx.input(|input| { input .raw @@ -572,13 +580,13 @@ impl Workbench { .map(|file| file.path().to_path_buf()) .collect() }); - if !dropped.is_empty() && self.settings.legal_accepted { + if !dropped.is_empty() { self.add_paths(dropped); } } fn shortcuts(&mut self, ctx: &Context) { - if !self.settings.legal_accepted { + if self.modal_blocks_input(ctx) { return; } let open = egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::O); diff --git a/senbei-io/src/android/memory.rs b/senbei-io/src/android/memory.rs new file mode 100644 index 0000000..ed604e5 --- /dev/null +++ b/senbei-io/src/android/memory.rs @@ -0,0 +1,334 @@ +//! Android recovery over bytes, for a front end that has no filesystem. +//! +//! The browser binding calls these. They run the same engines as the +//! path-based drivers in the parent module and describe the result through the +//! same profile helpers, so a library or a metadata blob is reported the same +//! way whichever front end handled it. +//! +//! Application context stays with the caller. A metadata blob is paired with a +//! module `0x0C` only when the caller passes one, and the caller is the one +//! that knows which library belongs to the same application. + +use anyhow::Context; +use senbei_engine::android::{ + ResourceLimits, extract_stage2_in_memory, probe_libil2cpp_profiled_with_limits, + restore_libil2cpp_in_memory, +}; +use senbei_engine::{LayoutKind, ProtectionProfile, ValidationStatus}; +use senbei_i18n::{Message, Msg}; + +use super::ValidationDiagnostics; +use crate::message::of_error; + +/// A protected library restored in memory. +#[derive(Debug)] +pub struct LibraryBytes { + /// The restored ELF image. + pub image: Vec, + /// The unwrapped metadata blob, when the restored image embeds one. + pub embedded_metadata: Option>, + /// Decoded module `0x0C`. It belongs to this library's application and is + /// what a v24 metadata blob of that application needs. + pub method_index_module: Option>, + /// Structural diagnostics for `image`. Advisory: the restore accepted it. + pub validation: ValidationDiagnostics, + /// Table counts of `image`, as the restore's own validation read them. + pub elf: ElfSummary, +} + +/// Table counts of a restored ELF image. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +pub struct ElfSummary { + pub sections: usize, + pub segments: usize, + pub dynamic_symbols: usize, + pub dynamic_relocations: usize, + pub pltgot_relocations: usize, +} + +/// What [`restore_library_bytes`] did with one input. +#[derive(Debug)] +pub enum LibraryOutcome { + Restored(LibraryBytes), + /// The probe did not match. The input is not a supported target. + NotProtected, + /// The probe was blocked by a ceiling, or the restore failed. + Failed(Message), +} + +/// Probe and restore one AArch64 library held in memory. +/// +/// The profile is returned in every case. A probe that does not match leaves +/// it `not_recognized` and nothing else runs. +pub fn restore_library_bytes( + input: &[u8], + verbose: bool, + limits: &ResourceLimits, +) -> (ProtectionProfile, LibraryOutcome) { + let (probe, matched) = probe_libil2cpp_profiled_with_limits(input, limits); + match matched { + Ok(true) => {} + Ok(false) => return (probe, LibraryOutcome::NotProtected), + Err(error) => { + let detail = of_error(&anyhow::Error::new(error)); + return (probe, LibraryOutcome::Failed(detail)); + } + } + match restore_matched_library(input, verbose, limits) { + Ok(restored) => { + let mut profile = crate::report::android_recovered_profile(); + profile.static_validation = if restored.validation.is_clean() { + ValidationStatus::Clean + } else { + ValidationStatus::Warnings + }; + profile.warnings.extend( + restored + .validation + .messages + .iter() + .cloned() + .map(Message::from), + ); + (profile, LibraryOutcome::Restored(restored)) + } + Err(error) => { + let detail = of_error(&error); + let mut profile = crate::report::android_failed_profile(&detail); + // The probe read this input, so its format and evidence are known. + profile.observed = probe.observed; + profile.evidence = probe.evidence; + (profile, LibraryOutcome::Failed(detail)) + } + } +} + +fn restore_matched_library( + input: &[u8], + verbose: bool, + limits: &ResourceLimits, +) -> anyhow::Result { + let extraction = + extract_stage2_in_memory(input, limits).context("extract stage-1/stage-2 payload")?; + let restored = restore_libil2cpp_in_memory(input, &extraction, verbose, limits) + .context("restore protected library")?; + Ok(LibraryBytes { + embedded_metadata: senbei_metadata::android::extract_embedded_metadata(&restored.bytes), + method_index_module: extraction.module(0x0c).map(<[u8]>::to_vec), + elf: ElfSummary { + sections: restored.validation.sections, + segments: restored.validation.segments, + dynamic_symbols: restored.validation.dynamic_symbols, + dynamic_relocations: restored.validation.dynamic_relocations, + pltgot_relocations: restored.validation.pltgot_relocations, + }, + validation: ValidationDiagnostics { + messages: restored.validation.diagnostics, + }, + image: restored.bytes, + }) +} + +/// What [`restore_metadata_bytes_profiled`] did with one blob. +/// +/// `layout` is the transform that ran. A blob that needed no change keeps it +/// here only: its profile claims no route, as an ordinary run's does. +#[derive(Debug)] +pub enum MetadataOutcome { + /// Protected fields were rewritten; `bytes` is the restored blob. + Restored { + bytes: Vec, + report: senbei_metadata::Report, + layout: LayoutKind, + }, + /// The transform ran and validated, and the blob needed no change. + Unchanged { + report: senbei_metadata::Report, + layout: LayoutKind, + }, + /// A format version this build leaves untouched by design. + Unsupported { + version: u32, + }, + Failed(Message), +} + +/// The module `0x0C` images the caller collected for a blob's application. +#[derive(Debug, Clone, Copy)] +pub enum ModuleBinding<'a> { + /// No library of the application yielded a module. + None, + /// Every library that yielded a module yielded this one. + One(&'a [u8]), + /// The libraries yielded this many different modules. + Conflicting { profiles: usize }, +} + +/// Restore one il2cpp metadata blob held in memory. +/// +/// Only a v24 blob consumes module `0x0C`, so only a v24 blob fails on a +/// missing or conflicting binding. The later layouts ignore it. +pub fn restore_metadata_bytes_profiled( + data: &[u8], + binding: ModuleBinding<'_>, +) -> (ProtectionProfile, MetadataOutcome) { + let identity = senbei_metadata::identify(data); + let method_index_module = match binding { + ModuleBinding::One(module) => Some(module), + ModuleBinding::None => None, + ModuleBinding::Conflicting { profiles } => { + if identity.is_some_and(|identity| identity.raw_version == 24) { + let detail = Message::with_text( + Msg::AmbiguousModule0c, + format!("ambiguous module 0x0C binding ({profiles} distinct profiles)"), + ); + let profile = crate::report::metadata_failed_profile( + identity, + LayoutKind::MetadataMethodIndices, + &detail, + ); + return (profile, MetadataOutcome::Failed(detail)); + } + None + } + }; + match super::restore_metadata_bytes_with_module(data, method_index_module) { + Ok((bytes, report, layout)) if report.remapped > 0 => ( + crate::report::metadata_recovered_profile(identity, layout), + MetadataOutcome::Restored { + bytes, + report, + layout, + }, + ), + Ok((_, report, layout)) => ( + crate::report::metadata_unchanged_profile(identity), + MetadataOutcome::Unchanged { report, layout }, + ), + Err(error) => match unsupported_version(&error) { + Some(version) => { + let mut profile = crate::report::metadata_unchanged_profile(identity); + profile.push_warning(Msg::MetadataLeftUntouched { version }); + (profile, MetadataOutcome::Unsupported { version }) + } + None => { + let detail = of_error(&error); + let profile = crate::report::metadata_failed_profile( + identity, + LayoutKind::MetadataStructural, + &detail, + ); + (profile, MetadataOutcome::Failed(detail)) + } + }, + } +} + +/// The version in a [`senbei_metadata::Error::UnsupportedVersion`] anywhere in +/// `error`'s chain. +fn unsupported_version(error: &anyhow::Error) -> Option { + error.chain().find_map(|cause| match cause.downcast_ref() { + Some(senbei_metadata::Error::UnsupportedVersion(version)) => Some(*version), + _ => None, + }) +} + +/// Application identity from a package's root `AndroidManifest.xml`: the +/// `package` name and its version. +/// +/// `bytes` is the manifest entry, plain or compiled. `truncated` says the +/// caller's bounded read stopped before the end of the entry, in which case no +/// identity is returned. +pub fn manifest_identity(bytes: &[u8], truncated: bool) -> Option<(String, String)> { + super::manifest::identity(bytes, truncated) +} + +#[cfg(test)] +mod tests { + use super::*; + use senbei_engine::{RecognitionStatus, RecoveryStatus}; + + fn metadata_header(version: u32) -> Vec { + let mut blob = 0xFAB1_1BAF_u32.to_le_bytes().to_vec(); + blob.extend_from_slice(&version.to_le_bytes()); + blob + } + + #[test] + fn an_ordinary_library_is_not_protected_and_nothing_runs() { + let (profile, outcome) = restore_library_bytes( + b"\x7fELF not a real image", + false, + &ResourceLimits::default(), + ); + assert!(matches!(outcome, LibraryOutcome::NotProtected)); + assert_eq!(profile.recognition, RecognitionStatus::NotRecognized); + assert!(profile.candidates.is_empty()); + assert_eq!(profile.recovery, RecoveryStatus::NotAttempted); + } + + #[test] + fn v24_metadata_without_its_module_fails_instead_of_skipping() { + let (profile, outcome) = + restore_metadata_bytes_profiled(&metadata_header(24), ModuleBinding::None); + let MetadataOutcome::Failed(detail) = outcome else { + panic!("a v24 blob with no module must fail: {outcome:?}"); + }; + assert_eq!(detail.msg(), Some(&Msg::NoModule0c)); + assert_eq!(profile.recognition, RecognitionStatus::Blocked); + assert_eq!(profile.recovery, RecoveryStatus::Failed); + assert_eq!(profile.static_validation, ValidationStatus::NotRun); + } + + #[test] + fn an_unsupported_version_is_left_untouched() { + let (profile, outcome) = + restore_metadata_bytes_profiled(&metadata_header(999), ModuleBinding::None); + assert!(matches!( + outcome, + MetadataOutcome::Unsupported { version: 999 } + )); + assert_eq!(profile.recognition, RecognitionStatus::NotRecognized); + assert_eq!(profile.recovery, RecoveryStatus::NotAttempted); + assert!(profile.errors.is_empty()); + assert_eq!(profile.warnings.len(), 1); + } + + #[test] + fn a_malformed_blob_fails_without_a_protection_verdict() { + let (profile, outcome) = + restore_metadata_bytes_profiled(&metadata_header(31), ModuleBinding::None); + assert!(matches!(outcome, MetadataOutcome::Failed(_))); + assert_eq!(profile.recognition, RecognitionStatus::Blocked); + assert!(profile.evidence.is_empty()); + assert!(profile.selected.is_none()); + } + + #[test] + fn conflicting_modules_stop_only_the_layout_that_needs_one() { + let conflicting = ModuleBinding::Conflicting { profiles: 2 }; + let (profile, outcome) = restore_metadata_bytes_profiled(&metadata_header(24), conflicting); + let MetadataOutcome::Failed(detail) = outcome else { + panic!("a v24 blob cannot choose between two modules: {outcome:?}"); + }; + assert_eq!(detail.msg(), Some(&Msg::AmbiguousModule0c)); + assert_eq!(profile.recovery, RecoveryStatus::Failed); + + // A layout that takes no module is decided by its own transform. + let (_, outcome) = restore_metadata_bytes_profiled(&metadata_header(31), conflicting); + let MetadataOutcome::Failed(detail) = outcome else { + panic!("a header-only blob is malformed: {outcome:?}"); + }; + assert_ne!(detail.msg(), Some(&Msg::AmbiguousModule0c)); + } + + #[test] + fn a_truncated_manifest_names_no_application() { + let manifest = br#""#; + assert_eq!( + manifest_identity(manifest, false), + Some(("com.example.app".to_owned(), "7".to_owned())) + ); + assert_eq!(manifest_identity(manifest, true), None); + } +} diff --git a/senbei-io/src/android/mod.rs b/senbei-io/src/android/mod.rs index b92a035..1e38bce 100644 --- a/senbei-io/src/android/mod.rs +++ b/senbei-io/src/android/mod.rs @@ -12,8 +12,9 @@ //! the blob is located by content and unwrapped //! ([`senbei_metadata::android::extract_embedded_metadata`]). //! -//! All functions in this module are native filesystem orchestration; the web -//! app (wasm) never touches them. +//! The functions in this module are native filesystem orchestration. The +//! browser binding has no filesystem and uses the byte-level entry points in +//! [`memory`], re-exported here. #[cfg(test)] mod resource_tests; @@ -23,6 +24,12 @@ mod tests; mod archive_limits; mod context; mod manifest; +mod memory; + +pub use memory::{ + ElfSummary, LibraryBytes, LibraryOutcome, MetadataOutcome, ModuleBinding, manifest_identity, + restore_library_bytes, restore_metadata_bytes_profiled, +}; use context::LibraryRestorer; diff --git a/senbei-io/src/job.rs b/senbei-io/src/job.rs index 9709f13..b31a940 100644 --- a/senbei-io/src/job.rs +++ b/senbei-io/src/job.rs @@ -2320,35 +2320,6 @@ fn apply_android_validation( report.stages.push(stage); } -/// Profile for a metadata blob whose transform ran, validated, and needed no -/// change. -/// -/// The route was really taken and the bytes really validated, so the attempt is -/// recorded — but a clean blob is no protection evidence, so recognition stays -/// `not_recognized` and no protection verdict is claimed. Without this an -/// inspection of an already-clean blob would say `not_attempted` while the -/// research section next to it showed the route and its report. -fn metadata_validated_unchanged_profile( - identity: Option, - route: senbei_engine::LayoutKind, -) -> senbei_engine::ProtectionProfile { - use senbei_engine::{AttemptOutcome, LayoutAttempt, ProtectionProfile}; - let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::metadata( - identity.map(|identity| identity.raw_version), - )); - profile.candidates = vec![LayoutAttempt { - layout: route, - outcome: AttemptOutcome::Succeeded, - warnings: Vec::new(), - errors: Vec::new(), - }]; - profile.selected = Some(route); - profile.recovery = senbei_engine::RecoveryStatus::Succeeded; - profile.static_validation = senbei_engine::ValidationStatus::NotRun; - profile.recognition = senbei_engine::RecognitionStatus::NotRecognized; - profile -} - /// Input report for one loose il2cpp metadata blob. fn metadata_input( input: &Path, @@ -2380,7 +2351,7 @@ fn metadata_input( // even though the status stays "nothing needed". entry.status = InputStatus::Skipped; entry.profile = Some(match report.research { - Some(_) => metadata_validated_unchanged_profile(identity, report.layout), + Some(_) => crate::report::metadata_validated_unchanged_profile(identity, report.layout), None => crate::report::metadata_unchanged_profile(identity), }); entry.stages.push( @@ -2412,7 +2383,7 @@ fn single_metadata_input( entry.profile = Some(match (dest.is_some(), research) { (true, _) => crate::report::metadata_recovered_profile(identity, layout), // The transform ran and validated; only the rewrite was unnecessary. - (false, true) => metadata_validated_unchanged_profile(identity, layout), + (false, true) => crate::report::metadata_validated_unchanged_profile(identity, layout), (false, false) => crate::report::metadata_unchanged_profile(identity), }); entry.outputs = dest diff --git a/senbei-io/src/report.rs b/senbei-io/src/report.rs index 3f49249..323d776 100644 --- a/senbei-io/src/report.rs +++ b/senbei-io/src/report.rs @@ -829,6 +829,34 @@ pub(crate) fn metadata_unchanged_profile( profile } +/// Profile for a metadata blob whose transform ran, validated, and needed no +/// change. +/// +/// The route was really taken and the bytes really validated, so the attempt is +/// recorded — but a clean blob is no protection evidence, so recognition stays +/// `not_recognized` and no protection verdict is claimed. Without this an +/// inspection of an already-clean blob would say `not_attempted` while the +/// research section next to it showed the route and its report. +pub(crate) fn metadata_validated_unchanged_profile( + identity: Option, + route: LayoutKind, +) -> ProtectionProfile { + let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::metadata( + identity.map(|identity| identity.raw_version), + )); + profile.candidates = vec![senbei_engine::LayoutAttempt { + layout: route, + outcome: AttemptOutcome::Succeeded, + warnings: Vec::new(), + errors: Vec::new(), + }]; + profile.selected = Some(route); + profile.recovery = RecoveryStatus::Succeeded; + profile.static_validation = ValidationStatus::NotRun; + profile.recognition = RecognitionStatus::NotRecognized; + profile +} + /// Profile for a metadata blob whose transform failed. pub(crate) fn metadata_failed_profile( identity: Option, diff --git a/senbei-wasm/Cargo.lock b/senbei-wasm/Cargo.lock index 148acad..069a11e 100644 --- a/senbei-wasm/Cargo.lock +++ b/senbei-wasm/Cargo.lock @@ -513,7 +513,9 @@ name = "senbei-wasm" version = "1.4.0" dependencies = [ "console_error_panic_hook", + "js-sys", "senbei-engine", + "senbei-i18n", "senbei-io", "senbei-metadata", "serde_json", diff --git a/senbei-wasm/Cargo.toml b/senbei-wasm/Cargo.toml index ef925c2..4a67b05 100644 --- a/senbei-wasm/Cargo.toml +++ b/senbei-wasm/Cargo.toml @@ -13,11 +13,32 @@ crate-type = ["cdylib"] senbei-io = { path = "../senbei-io" } senbei-metadata = { path = "../senbei-metadata" } senbei-engine = { path = "../senbei-engine" } +senbei-i18n = { path = "../senbei-i18n" } serde_json = "1" wasm-bindgen = "0.2" +js-sys = "0.3" console_error_panic_hook = "0.1" [profile.release] opt-level = "z" lto = true codegen-units = 1 + +# The whole module is built for size. The crates below hold the loops a +# recovery spends its time in (ciphers, decompression, hashing, table scans); +# built for size they lose inlining and run about a third slower, so they are +# built for speed. +[profile.release.package.senbei-crypto] +opt-level = 3 + +[profile.release.package.senbei-elf] +opt-level = 3 + +[profile.release.package.senbei-engine] +opt-level = 3 + +[profile.release.package.aes] +opt-level = 3 + +[profile.release.package.sha2] +opt-level = 3 diff --git a/senbei-wasm/src/lib.rs b/senbei-wasm/src/lib.rs index 17aff07..c11d93e 100644 --- a/senbei-wasm/src/lib.rs +++ b/senbei-wasm/src/lib.rs @@ -1,11 +1,40 @@ //! WebAssembly bindings for the senbei unpacker core. //! //! Everything here is I/O-free: the browser hands in file bytes and gets -//! unpacked file bytes back. No network, no filesystem, no uploads. +//! recovered bytes back. No network, no filesystem, no uploads. +//! +//! One job runs per module instance. The page starts a disposable worker for +//! each job, because a Rust panic is a trap in WebAssembly and a trapped +//! instance cannot be used again. -use senbei_engine::{IntegrityReport, IntegritySeverity, ProtectionProfile, UnpackError}; +use std::cell::RefCell; +use std::rc::Rc; + +use senbei_engine::android::ResourceLimits; +use senbei_engine::progress::{self, Event}; +use senbei_engine::{IntegrityReport, IntegritySeverity, ProtectionProfile}; +use senbei_i18n::{Lang, Localize, Message, Msg, Step}; +use senbei_io::android::{LibraryOutcome, MetadataOutcome, ModuleBinding}; +use serde_json::{Value, json}; use wasm_bindgen::prelude::*; +/// Lines kept from one job's verbose progress. A library with many encoded +/// segments reports one line each; past this the log says it was cut. +const LOG_LINE_LIMIT: usize = 4000; + +/// Ceilings for one Android job in a 32-bit address space. +/// +/// One decoded entry or output image may reach 1 GiB. The task total counts +/// decoded bytes that are written and released as the restore proceeds, so it +/// sits above what the instance can hold at once; the instance's own memory is +/// the bound that matters there. +const BROWSER_LIMITS: ResourceLimits = ResourceLimits { + max_entry_bytes: 1 << 30, + max_total_bytes: 4 << 30, + max_entries: 100_000, + max_depth: 32, +}; + /// Install a panic hook that forwards Rust panic messages to the browser /// console (and to the JS error), instead of a bare `unreachable` trap. #[wasm_bindgen(start)] @@ -13,136 +42,133 @@ pub fn init_panic_hook() { console_error_panic_hook::set_once(); } -/// Serialize a profile for the JS layer. +/// One input file, filled in place. /// -/// `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. +/// The page appends a file to this in slices, so the file is held once, in +/// this instance's memory, and never as a second whole copy on the JS side. #[wasm_bindgen] -pub struct UnpackResult { - kind: String, +pub struct InputBuffer { bytes: Vec, - suspect: bool, - issues: Vec, - companion: bool, - severities: Vec, - fatal: bool, - profile_json: Option, } #[wasm_bindgen] -impl UnpackResult { - /// Detected module kind: `"native-exe"`, `"managed-exe"`, `"native-dll"`, - /// or `"managed-dll"`. - #[wasm_bindgen(getter)] - pub fn kind(&self) -> String { - self.kind.clone() +impl InputBuffer { + /// Reserve room for `capacity` bytes. Throws when the instance cannot. + #[wasm_bindgen(constructor)] + pub fn new(capacity: usize) -> Result { + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(capacity) + .map_err(|_| JsError::new("not enough memory for this input"))?; + Ok(Self { bytes }) } - /// The unpacked image bytes. - #[wasm_bindgen(getter)] - pub fn bytes(&self) -> Vec { - self.bytes.clone() + /// Append the next slice. Throws when it would pass the reserved size. + pub fn append(&mut self, chunk: &[u8]) -> Result<(), JsError> { + if chunk.len() > self.bytes.capacity() - self.bytes.len() { + return Err(JsError::new("input is larger than its declared size")); + } + self.bytes.extend_from_slice(chunk); + Ok(()) } - /// True when the static integrity check flagged the output as likely - /// broken at runtime. The bytes are still the best available. + /// Bytes appended so far. #[wasm_bindgen(getter)] - pub fn suspect(&self) -> bool { - self.suspect + pub fn length(&self) -> usize { + self.bytes.len() } - /// Human-readable integrity defects (empty when the check is clean). - #[wasm_bindgen(getter)] - pub fn issues(&self) -> Vec { - self.issues.clone() - } - - /// True when the input was spliced from an external-companion (`._`) - /// payload. - #[wasm_bindgen(getter)] - 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() + /// SHA-256 of the bytes appended so far, as lowercase hex. + pub fn sha256(&self) -> String { + senbei_io::android::content_identity(&self.bytes) } } -/// Result of de-obfuscating an il2cpp `global-metadata.dat`. +/// What one job produced. +/// +/// `info` is a JSON document with everything except the bytes. The recovered +/// bytes are handed out as views of this instance's memory, so the page can +/// copy them straight into a `Blob` without a second copy on the JS heap. A +/// view is valid only until the next call into this module. #[wasm_bindgen] -pub struct MetadataResult { - bytes: Vec, - version: u32, - methods: usize, - remapped: usize, - modules: usize, +pub struct Outcome { + info: String, + image: Vec, + embedded_metadata: Option>, + module: Option>, } #[wasm_bindgen] -impl MetadataResult { - /// The (possibly rewritten) metadata bytes. +impl Outcome { + /// The job's report as JSON: `status`, `kind`, `error`, `note`, `profile`, + /// `routes`, `findings`, `warnings`, `errors`, `metadata`, `elf`, and + /// `log`. + /// + /// `status` is `recovered`, `unchanged`, `unsupported`, `not_protected`, + /// or `failed`. `profile` is the recovery profile in the format the CLI's + /// JSON report uses; its messages are English. `routes`, `warnings`, + /// `errors`, `error`, and `note` repeat the profile's messages as + /// `{ text, local }`, where `local` is the wording in the page language + /// when the message has one. #[wasm_bindgen(getter)] - pub fn bytes(&self) -> Vec { - self.bytes.clone() + pub fn info(&self) -> String { + self.info.clone() } - #[wasm_bindgen(getter)] - pub fn version(&self) -> u32 { - self.version + /// A view of the recovered image or metadata blob. Empty unless `status` + /// is `recovered`. + pub fn image(&self) -> js_sys::Uint8Array { + // SAFETY: the view borrows `self.image`, which this object owns and + // never reallocates. The caller reads it before calling back into the + // module, as the type documents. + unsafe { js_sys::Uint8Array::view(&self.image) } } - /// Total method-definition entries in the metadata. - #[wasm_bindgen(getter)] - pub fn methods(&self) -> usize { - self.methods + /// SHA-256 of the recovered image, as lowercase hex. + pub fn image_sha256(&self) -> String { + senbei_io::android::content_identity(&self.image) } - /// Method tokens actually rewritten (0 means the input was already - /// de-obfuscated and the bytes are unchanged). - #[wasm_bindgen(getter)] - pub fn remapped(&self) -> usize { - self.remapped + /// A view of the metadata blob a restored Android library carried inside + /// it, when it carried one. + pub fn embedded_metadata(&self) -> Option { + // SAFETY: as for `image`. + self.embedded_metadata + .as_deref() + .map(|bytes| unsafe { js_sys::Uint8Array::view(bytes) }) } - /// Modules (images) owning at least one method. - #[wasm_bindgen(getter)] - pub fn modules(&self) -> usize { - self.modules + /// SHA-256 of the embedded metadata blob, when there is one. + pub fn embedded_metadata_sha256(&self) -> Option { + self.embedded_metadata + .as_deref() + .map(senbei_io::android::content_identity) } + + /// Decoded module `0x0C` of a restored Android library. A v24 metadata + /// blob of the same application needs it. + pub fn take_module(&mut self) -> Option> { + self.module.take() + } +} + +fn lang_of(tag: &str) -> Lang { + Lang::from_tag(tag).unwrap_or(Lang::En) +} + +/// A message as the page shows it: the recorded English, and the wording in +/// `lang` when the message has a catalog entry there. +fn message_value(message: &Message, lang: Lang) -> Value { + let local = + (lang != Lang::En && message.msg().is_some()).then(|| message.localized(lang).into_owned()); + json!({ "text": message.text(), "local": local }) +} + +fn messages_value(messages: &[Message], lang: Lang) -> Value { + messages + .iter() + .map(|message| message_value(message, lang)) + .collect() } fn kind_str(kind: senbei_engine::Kind) -> &'static str { @@ -154,33 +180,176 @@ 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: Vec = report - .issues +/// The integrity findings, in the checker's order. +fn findings_value(report: &IntegrityReport) -> Value { + report + .findings .iter() - .map(|issue| issue.to_string()) - .collect(); - 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) + .zip(&report.issues) + .map(|(finding, issue)| { + json!({ + "severity": match finding.severity { + IntegritySeverity::Fatal => "fatal", + IntegritySeverity::Warning => "warning", + }, + "message": issue.to_string(), + }) + }) + .collect() } -/// Classify a file's bytes without unpacking. +/// The name the workbench's catalogs give a step, where they have one. +/// +/// The desktop window titles these steps in its own words and the page shows +/// the same titles, so it looks them up by this name. Steps that share a title +/// share a name. +fn step_key(step: &Step) -> Option<&'static str> { + Some(match step { + Step::DecryptHeader => "decrypt_header", + Step::DecryptPayload => "decrypt_payload", + Step::LocateConfig | Step::Pe32LocateConfig => "locate_config", + Step::DecryptStage2 => "decrypt_stage2", + Step::DecryptStages3To5 => "decrypt_stages_3_5", + Step::DecryptSections | Step::DecryptSectionsNewLayout => "decrypt_sections", + Step::LoadSections => "load_sections", + Step::DecryptImports | Step::Pe32Imports => "decrypt_imports", + Step::RebuildHeaders => "rebuild_headers", + Step::Pe32Stages => "pe32_stages", + Step::Pe32EighthStage => "pe32_eighth", + Step::Pe32Load => "pe32_load", + Step::Pe32Text { .. } => "pe32_text", + Step::Pe32TextSkip => "pe32_text_skip", + Step::Pe32Rebuild => "pe32_rebuild", + Step::InitKeys => "init_keys", + Step::DecryptKeyTable => "decrypt_key_table", + Step::DecryptPrimary => "decrypt_primary", + Step::RelocsParams => "relocs_params", + Step::DecryptBlock1 => "decrypt_block1", + Step::DecryptBlocks2To3 => "decrypt_block23", + Step::DecryptBlock4 => "decrypt_block4", + Step::DllSections => "dll_sections", + Step::FixHeaders => "fix_headers", + Step::AndroidPrimary => "android_primary", + Step::AndroidAuxiliary => "android_aux", + Step::AndroidTables => "android_tables", + _ => return None, + }) +} + +/// Run `job` with its verbose progress collected. +/// +/// A step is logged as `{"ms", "step": title, "key": name, "i": n, "of": +/// total}` with its title in `lang` and its catalog name from [`step_key`]; +/// `i` and `of` are null for the unnumbered Android stages. A detail line is +/// `{"ms", "detail": text}`; those are technical and stay English. `ms` is the +/// time since the job started. +/// `on_step`, when given, is called with `(title, i, of, name)` as each step +/// starts, so the page can show where a long job is. +fn with_log( + lang: Lang, + on_step: Option, + job: impl FnOnce() -> R, +) -> (R, Vec) { + let log = Rc::new(RefCell::new(Vec::new())); + let sink_log = Rc::clone(&log); + let started = js_sys::Date::now(); + let result = progress::with_sink( + move |event| { + let ms = (js_sys::Date::now() - started).max(0.0).round(); + let line = match event { + Event::Step { step, position } => { + let title = step.localize(lang); + let key = step_key(step); + let (i, of) = position.unzip(); + if let Some(on_step) = &on_step { + let arguments = js_sys::Array::of4( + &JsValue::from_str(&title), + &i.map_or(JsValue::NULL, JsValue::from), + &of.map_or(JsValue::NULL, JsValue::from), + &key.map_or(JsValue::NULL, JsValue::from_str), + ); + // A failed callback must not stop the recovery. + let _ = on_step.apply(&JsValue::NULL, &arguments); + } + json!({ "ms": ms, "step": title, "key": key, "i": i, "of": of }) + } + Event::Detail(line) => json!({ "ms": ms, "detail": line.trim() }), + }; + let mut log = sink_log.borrow_mut(); + match log.len() { + len if len < LOG_LINE_LIMIT => log.push(line), + LOG_LINE_LIMIT => log.push(json!({ "truncated": true })), + _ => {} + } + }, + job, + ); + let log = log.take(); + (result, log) +} + +struct Info<'a> { + status: &'static str, + kind: Option<&'a str>, + profile: &'a ProtectionProfile, + error: Option<&'a Message>, + lang: Lang, + log: Vec, +} + +impl Info<'_> { + /// The fields every job reports. Job-specific ones are added by the caller. + fn value(self) -> Value { + // Why an input that did not fail has no output. + let note = match self.status { + "unchanged" => Some(Message::new(Msg::TransformNoop)), + "not_protected" => Some(Message::new(Msg::NotProtected)), + _ => None, + }; + let routes: Vec = self + .profile + .candidates + .iter() + .map(|attempt| { + json!({ + "layout": attempt.layout, + "outcome": attempt.outcome, + "warnings": messages_value(&attempt.warnings, self.lang), + "errors": messages_value(&attempt.errors, self.lang), + }) + }) + .collect(); + json!({ + "status": self.status, + "kind": self.kind, + "error": self.error.map(|error| message_value(error, self.lang)), + "note": note.map(|note| message_value(¬e, self.lang)), + "profile": self.profile, + "routes": routes, + "warnings": messages_value(&self.profile.warnings, self.lang), + "errors": messages_value(&self.profile.errors, self.lang), + "findings": [], + "suspect": false, + "companion": false, + "metadata": null, + "elf": null, + "log": self.log, + }) + } +} + +impl Outcome { + fn new(info: Value) -> Self { + Self { + info: info.to_string(), + image: Vec::new(), + embedded_metadata: None, + module: None, + } + } +} + +/// Classify a file from its first bytes without unpacking. /// /// Returns `"native-exe"`, `"managed-exe"`, `"native-dll"`, `"managed-dll"`, /// `"metadata"` (an il2cpp `global-metadata.dat`), or `undefined` for @@ -209,426 +378,229 @@ pub fn detect(input: &[u8]) -> Option { /// 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 -/// `._` external-companion payload (pass `null`/`undefined` when there -/// is none). Throws a string error when the input is not a supported -/// CrackProof file or is corrupt. -#[wasm_bindgen] -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::from_image(r)) -} - -/// De-obfuscate the method tokens of an il2cpp `global-metadata.dat`. -/// -/// The transform is idempotent: an already-clean metadata comes back -/// byte-identical with `remapped == 0`. Throws a string error for non-metadata -/// input, an unsupported format version, or a malformed layout. -#[wasm_bindgen] -pub fn deobfuscate_metadata(data: &[u8]) -> Result { - let (bytes, report) = - senbei_metadata::deobfuscate(data).map_err(|e| JsError::new(&e.to_string()))?; - Ok(MetadataResult { - bytes, - version: report.version, - methods: report.methods, - remapped: report.remapped, - modules: report.modules, - }) -} - -/// 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) -} - -type MetadataTransform = Result<(Vec, senbei_metadata::Report), senbei_metadata::Error>; - -/// 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, MetadataTransform) { - 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; + let profile = match senbei_metadata::identify(input) { + Some(identity) => { + let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::metadata( + Some(identity.version.raw()), + )); + profile.push_warning( + "the il2cpp metadata magic and version identify a file format; \ + they do not establish that the file is protected", + ); + profile } - 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"); + None => senbei_engine::inspect_profile(input), + }; + serde_json::to_string(&profile).unwrap_or_else(|_| "null".to_string()) +} + +/// Unpack a protected Windows module. +/// +/// `companion` is the `._` external payload when there is one. +/// `force_exe` selects the EXE-only route: the page's retry for a DLL whose +/// DLL-first probe trapped. `lang` is the page language for step titles and +/// message wording, and `on_step` receives each step title as it starts. +#[wasm_bindgen] +pub fn unpack_pe( + input: &InputBuffer, + companion: Option, + force_exe: bool, + lang: &str, + on_step: Option, +) -> Outcome { + let lang = lang_of(lang); + let companion = companion.as_ref().map(|buffer| buffer.bytes.as_slice()); + let ((profile, result), log) = with_log(lang, on_step, || { + if force_exe { + senbei_io::job::unpack_bytes_force_exe_profiled_v(&input.bytes, companion, true) + } else { + senbei_io::job::unpack_bytes_profiled_v(&input.bytes, companion, true) + } + }); + let observed_kind = profile.observed.kind.map(kind_str); + match result { + Ok(image) => { + let mut info = Info { + status: "recovered", + kind: Some(kind_str(image.kind)), + profile: &profile, + error: None, + lang, + log, + } + .value(); + info["findings"] = findings_value(&image.integrity); + info["suspect"] = json!(!image.integrity.ok()); + info["companion"] = json!(image.companion); + Outcome { + image: image.bytes, + ..Outcome::new(info) + } } Err(error) => { - // A version/magic match plus a failed transform cannot establish - // that protected method fields were present in this input. - profile.recognition = RecognitionStatus::Blocked; - profile.candidates = vec![LayoutAttempt { - layout: route, - outcome: AttemptOutcome::Failed, - warnings: Vec::new(), - errors: vec![error.to_string().into()], - }]; - profile.recovery = RecoveryStatus::Failed; - profile.push_error(error.to_string()); - } - } - profile.static_validation = ValidationStatus::NotRun; - (version, profile, result) -} - -#[cfg(test)] -mod metadata_profile_tests { - use super::*; - use senbei_engine::{RecognitionStatus, RecoveryStatus, ValidationStatus}; - - #[test] - fn failed_metadata_transform_has_no_protection_verdict() { - for version in [31u32, 999] { - let mut input = 0xFAB1_1BAFu32.to_le_bytes().to_vec(); - input.extend_from_slice(&version.to_le_bytes()); - let (observed, profile, result) = metadata_outcome(&input); - assert!(result.is_err()); - assert_eq!(observed, Some(version)); - assert_eq!(profile.recognition, RecognitionStatus::Blocked); - assert!(profile.evidence.is_empty()); - assert_eq!(profile.recovery, RecoveryStatus::Failed); - assert_eq!(profile.static_validation, ValidationStatus::NotRun); - assert!(profile.selected.is_none()); - } - } -} - -/// 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. -#[wasm_bindgen] -pub fn unpack_file_force_exe( - input: &[u8], - companion: Option>, -) -> Result { - let r = senbei_io::job::unpack_bytes_force_exe(input, companion.as_deref()) - .map_err(|e| JsError::new(&e.to_string()))?; - 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, - } + let error = error.message(); + let mut info = Info { + status: "failed", + kind: observed_kind, + profile: &profile, + error: Some(&error), + lang, + log, } - 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, - }, + .value(); + info["companion"] = json!(profile.observed.external_companion); + Outcome::new(info) } } } + +/// Probe an AArch64 library for the protection, without restoring it. +/// +/// Returns the probe's profile as JSON. `recognition` is `recognized` for a +/// protected library, `not_recognized` for an ordinary one, and `blocked` when +/// a ceiling stopped the probe before it could tell. The probe needs the whole +/// file: the payload is found through the section table at its end. +#[wasm_bindgen] +pub fn probe_library(input: &InputBuffer) -> String { + let (profile, _) = + senbei_engine::android::probe_libil2cpp_profiled_with_limits(&input.bytes, &BROWSER_LIMITS); + serde_json::to_string(&profile).unwrap_or_else(|_| "null".to_string()) +} + +/// Probe and restore a protected Android AArch64 library. +/// +/// A library the probe does not match is reported as `not_protected` and +/// nothing else runs. A restored library may also carry an embedded metadata +/// blob and module `0x0C`; see [`Outcome`]. +#[wasm_bindgen] +pub fn restore_library( + input: &InputBuffer, + lang: &str, + on_step: Option, +) -> Outcome { + let lang = lang_of(lang); + let ((profile, outcome), log) = with_log(lang, on_step, || { + senbei_io::android::restore_library_bytes(&input.bytes, true, &BROWSER_LIMITS) + }); + let info = |status, error| { + Info { + status, + kind: Some("android-library"), + profile: &profile, + error, + lang, + log, + } + .value() + }; + match outcome { + LibraryOutcome::Restored(restored) => { + let mut info = info("recovered", None); + info["elf"] = json!(restored.elf); + Outcome { + image: restored.image, + embedded_metadata: restored.embedded_metadata, + module: restored.method_index_module, + ..Outcome::new(info) + } + } + LibraryOutcome::NotProtected => Outcome::new(info("not_protected", None)), + LibraryOutcome::Failed(error) => Outcome::new(info("failed", Some(&error))), + } +} + +/// Restore the method tokens or method indices of an il2cpp +/// `global-metadata.dat`. +/// +/// `module` is module `0x0C` of the same application, when the page has +/// exactly one. `conflicting` is the number of different modules that +/// application's libraries yielded, when it is more than one. Only a v24 blob +/// needs a module, so only a v24 blob fails without one. `unchanged` means the +/// blob was already canonical and no bytes are returned. +#[wasm_bindgen] +pub fn restore_metadata( + input: &InputBuffer, + module: Option>, + conflicting: usize, + lang: &str, +) -> Outcome { + let lang = lang_of(lang); + let binding = match &module { + Some(module) => ModuleBinding::One(module), + None if conflicting > 1 => ModuleBinding::Conflicting { + profiles: conflicting, + }, + None => ModuleBinding::None, + }; + let (profile, outcome) = + senbei_io::android::restore_metadata_bytes_profiled(&input.bytes, binding); + let info = |status, + error, + report: Option<&senbei_metadata::Report>, + layout: Option| { + let mut info = Info { + status, + kind: Some("metadata"), + profile: &profile, + error, + lang, + log: Vec::new(), + } + .value(); + info["metadata"] = match report { + Some(report) => json!({ + "version": report.version, + "methods": report.methods, + "remapped": report.remapped, + "modules": report.modules, + // The transform that ran, also for a blob it left as it was. + "layout": layout, + }), + None => json!({ "version": profile.observed.metadata_version }), + }; + // What this format version allows, as the native report records it. + info["metadata"]["identity"] = json!(senbei_metadata::identify(&input.bytes)); + info + }; + match outcome { + MetadataOutcome::Restored { + bytes, + report, + layout, + } => Outcome { + image: bytes, + ..Outcome::new(info("recovered", None, Some(&report), Some(layout))) + }, + MetadataOutcome::Unchanged { report, layout } => { + Outcome::new(info("unchanged", None, Some(&report), Some(layout))) + } + MetadataOutcome::Unsupported { .. } => { + Outcome::new(info("unsupported", None, None, None)) + } + MetadataOutcome::Failed(error) => Outcome::new(info("failed", Some(&error), None, None)), + } +} + +/// Application identity from a package's root `AndroidManifest.xml`. +/// +/// Returns `[package, version]`, or `undefined` when the manifest names no +/// application. `truncated` says the page's bounded read stopped before the +/// end of the entry; a truncated manifest names nothing. +#[wasm_bindgen] +pub fn manifest_identity(manifest: &[u8], truncated: bool) -> Option> { + senbei_io::android::manifest_identity(manifest, truncated) + .map(|(package, version)| vec![package, version]) +} + +/// Why a package with an entry name that would leave it is refused. +/// +/// The page lists packages itself, so it is the page that finds such an entry; +/// this gives it the engine's own message for that, as `{"text", "local"}` +/// JSON with `local` in `lang`. +#[wasm_bindgen] +pub fn unsafe_package_entry(package: &str, lang: &str) -> String { + let message = Message::new(Msg::UnsafePackageEntry { + package: package.to_owned(), + }); + message_value(&message, lang_of(lang)).to_string() +} diff --git a/web/README.md b/web/README.md index c952f19..00eda7d 100644 --- a/web/README.md +++ b/web/README.md @@ -1,15 +1,22 @@ # Senbei Web -Senbei runs in the browser through the `senbei-wasm` crate. Files are read locally, unpacked in a worker, and offered back as downloads; no server receives input bytes. +Senbei runs in the browser through the `senbei-wasm` crate. Files are read locally, recovered in a Web Worker, and kept in the tab for download; no server receives input bytes. ## Features -- Protected `.exe` and `.dll` files produce `.unpack.*` downloads. -- External `.exe._` and `.dll._` companions are paired by filename. -- `global-metadata.dat` produces `global-metadata.unpack.dat` when tokens change. -- Each output receives the same static integrity check as the CLI. +- Protected `.exe` and `.dll` files, with `.exe._` and `.dll._` companions paired by path. +- Protected Android AArch64 `.so` libraries, including the metadata blob a library embeds. +- `global-metadata.dat`, bound to module `0x0C` of its application when the format needs it. +- `.apk`, `.apks`, and `.xapk` packages: the manifest is read first, and only `.so` and `global-metadata.dat` entries are extracted. +- Folders, picked or dropped. A scan opens only files whose names can be targets and never enters an `unpack` directory. +- Download outputs individually or together in a ZIP with the unfiltered input logs. Where the browser can write to a folder, Senbei saves the outputs and a timestamped `senbei-*.log` under `unpack/` in the selected folder. +- The interface follows the desktop workbench and its five languages. -Every unpack uses a disposable Web Worker so a WebAssembly trap cannot freeze the page. A trapped DLL can be retried through the forced-EXE path, matching native routing. +Every recovery runs in its own worker. The worker exits when the job finishes or traps, so a WebAssembly trap does not take down the page and the worker's memory can be reclaimed. A trapped DLL is retried through the EXE-only route, matching native routing. + +**Add folder** can use the browser's folder input even when the File System Access API is unavailable. Drag-and-drop scans require the browser to expose directory entries. Saving to a folder requires the File System Access API and write permission. If Chromium refuses to write some file types directly, including `.dll`, Senbei puts those files in a `senbei-remaining.*.zip` in `unpack/`. Extract it there to put them beside the files saved directly. All outputs remain downloadable from the tab. + +The browser shows Overview and Log, plus Entries for packages. Use the desktop app for Dry run, Inspect, and the Research, Hex, and Compare views. ## Build @@ -18,8 +25,26 @@ cd senbei-wasm wasm-pack build --target web --release --out-dir ../web/pkg ``` -Serve `web/` with a static HTTP server, for example `python -m http.server -d web 8000`. Opening `index.html` with `file://` does not work because browser modules require HTTP. +Serve `web/` with a static HTTP server, for example `python -m http.server -d web 8000`. Opening `index.html` with `file://` does not work because browser modules require HTTP. `node web/tools/stage.mjs ` copies the files the site needs, and only those, into ``. + +## Test + +```cmd +npm test --prefix web +``` + +The tests cover the pure modules under Node. `senbei-cli/tests/wasm_parity.rs` compares the binding with the native byte API. ## Layout -`senbei-wasm/src/lib.rs` contains the bindings. `web/app.js` manages the dropzone and downloads, `web/worker.js` runs one unpack job per worker, and `web/pkg/` contains ignored wasm-pack output. +| Path | Contents | +| --- | --- | +| `senbei-wasm/src/lib.rs` | The bindings: in-memory recovery for PE files, Android libraries, and metadata. | +| `web/app.js`, `web/run.js`, `web/output.js` | Browser events, adding inputs, the run queue, and saving outputs. | +| `web/view.js`, `web/detail.js`, `web/ui.js` | Workbench, detail pane, and shared UI components. | +| `web/state.js` | Inputs, selection, and results kept in the tab. | +| `web/engine.js`, `web/worker.js` | The compiled module shared between workers, and one recovery per worker. | +| `web/scan.js`, `web/package.js`, `web/zip.js` | Folder walking, package inventory, and ZIP reading and writing over `Blob`. | +| `web/model.js`, `web/report.js` | Naming and pairing rules shared with the native front ends, and the JSON report. | +| `web/i18n/` | Language catalogs generated by `web/tools/gen-i18n.mjs` from the desktop wording, plus `web-strings.json` for browser-only text. | +| `web/pkg/` | Ignored `wasm-pack` output. | diff --git a/web/app.js b/web/app.js index a6b4d76..ca044c1 100644 --- a/web/app.js +++ b/web/app.js @@ -1,723 +1,963 @@ -import init, { detect, inspect_profile_json } from './pkg/senbei_wasm.js'; +// The page: adding inputs, scanning folders, and handing results back. What is +// shown is in `view.js` and `detail.js`, what is held is in `state.js`, and +// running the recoveries is in `run.js`. + +import { LANGUAGES, language, loadLanguage, t } from './i18n.js'; import { - DEFAULT_INPUT_LIMIT_BYTES, - MAX_INPUT_LIMIT_MIB, - MIN_INPUT_LIMIT_MIB, - buildReport, - describeFindings, - describeObserved, - describeStages, - formatBytes, + VERSION, + allItems, + allOutputs, + find, + fullPath, + isBusy, + makeEntries, + makeGroup, + makeItem, + onChange, + outputBusy, + state, + targets, +} from './state.js'; +import * as view from './view.js'; +import { shownPath } from './ui.js'; +import { + DEFAULT_LIMIT_MIB, + MIN_SIZE, + PREFIX_SIZE, + baseName, + candidateKind, + isCompanionName, + languageFor, parseLimitMiB, - planReadBudget, - reportFileName, - serializeReport, -} from './report.js'; + sniff, +} from './model.js'; +import { Prober, loadEngine } from './engine.js'; +import { downloadArchive } from './output.js'; +import { collect, fileListRoot, walkEntry, walkFileList } from './scan.js'; +import { buildReport, reportFileName, serializeReport } from './report.js'; +import { cancelRun, pageError, saveAll, startRun } from './run.js'; -const dropzone = document.getElementById('dropzone'); -const picker = document.getElementById('picker'); -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'); - -await init(); - -// --- Legal gate: the page is unusable until the notice is acknowledged. --- -legalAccept.addEventListener('click', () => legalOverlay.remove()); -legalLink.addEventListener('click', (e) => { - e.preventDefault(); - if (!document.getElementById('legal-overlay')) { - document.body.appendChild(legalOverlay); - } -}); - -// --- File list: one row per module. Companions (`X._`) never get their own --- -// --- row once their base module `X` is present — they show as a badge on --- -// --- the base row. Rows are black while staged, show an animated blue --- -// --- progress bar while unpacking, and turn green (success) or red --- -// --- (failure) at the end; success rows gain a download button. --- - -// --- Row DOM is updated INCREMENTALLY: rows are created once and patched --- -// --- in place. Rebuilding the list on every change would restart the --- -// --- entrance animation of every row and reset the unpack shimmer. --- - -/** name -> { - * file: File, - * kind: string|undefined, // detect() result; undefined for `._` files - * 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(); - -/** name -> row
  • element (companions merged into their base have none) */ -const rowEls = new Map(); - -const KIND_LABEL = { - 'native-exe': 'protected native EXE', - 'managed-exe': 'protected managed EXE', - 'native-dll': 'protected native DLL', - 'managed-dll': 'protected managed DLL', - metadata: 'il2cpp metadata', - 'android-package': - 'Android app package — the web build cannot unpack these yet; use the senbei CLI', - 'android-so': - 'Android AArch64 library — the web build cannot unpack these yet; use the senbei CLI', +const $ = (id) => document.getElementById(id); +const el = { + topbar: $('topbar'), + main: $('main'), + inputs: $('inputs'), + detail: $('detail'), + status: $('status'), + cancel: $('cancel'), + menu: $('menu'), + dragover: $('dragover'), + legal: $('legal'), + settings: $('settings'), + pickFiles: $('pick-files'), + pickFolder: $('pick-folder'), + chips: null, + list: null, + search: null, + clear: null, }; -// Android targets are recognized by extension so the row can explain the -// situation instead of reporting a protected file as unrecognized: the -// Android pipeline is filesystem orchestration (senbei-io) with no wasm -// build, so these files need the CLI. The pseudo-kinds are labels only — -// they never reach the worker. -const ANDROID_KIND = { - apk: 'android-package', - apks: 'android-package', - xapk: 'android-package', - so: 'android-so', -}; +// ---------- settings that outlive the tab ---------- -const COMPANION_SVG = - ''; +const STORE = { language: 'senbei.language', limit: 'senbei.limit-mib', legal: 'senbei.legal-accepted' }; -const DOWNLOAD_SVG = - ''; - -dropzone.addEventListener('click', () => picker.click()); -dropzone.addEventListener('keydown', (e) => { - if (e.key === 'Enter' || e.key === ' ') picker.click(); -}); -picker.addEventListener('change', () => { - stageFiles(picker.files); - picker.value = ''; -}); -dropzone.addEventListener('dragover', (e) => { - e.preventDefault(); - dropzone.classList.add('over'); -}); -dropzone.addEventListener('dragleave', () => dropzone.classList.remove('over')); -dropzone.addEventListener('drop', (e) => { - e.preventDefault(); - dropzone.classList.remove('over'); - 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 - // them, so an await before this point silently drops every file after the - // first. - const snapshot = [...list]; - for (const file of snapshot) { - // Detection only needs the file header (key table at offset 4096 plus - // the PE header fields); read a small slice, not the whole file. - const head = new Uint8Array(await file.slice(0, 65536).arrayBuffer()); - // Companions are ciphertext fragments; detect() only makes sense on the - // base module, so skip it for `._` files. Android targets short-circuit - // detect() as well: an ELF/zip never classifies as a protected PE, and - // the row must carry the android pseudo-kind for its status line. - const ext = file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase(); - const kind = file.name.endsWith('._') - ? undefined - : (ANDROID_KIND[ext] ?? detect(head)); - const old = files.get(file.name); - files.set(file.name, { - file, - kind, - state: 'staged', - 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); - } - 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; +function stored(key) { try { - const parsed = JSON.parse(inspect_profile_json(head)); - return parsed && typeof parsed === 'object' ? parsed : null; + return localStorage.getItem(key); } 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': - 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 entry.kind === 'metadata' ? 'de-obfuscating…' : 'unpacking…'; - case 'ok': - case 'err': - case 'blocked': - return entry.note; +function store(key, value) { + try { + if (value === null) localStorage.removeItem(key); + else localStorage.setItem(key, value); + } catch { + // Storage can be off; the setting then lasts for this visit. } } -/** - * 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)]; +let accepted = stored(STORE.legal) === '1'; + +// ---------- rendering ---------- + +const shown = new WeakMap(); + +function focusKey(node) { + const { act, id } = node.dataset ?? {}; + if (act) return `[data-act="${act}"]${id ? `[data-id="${CSS.escape(id)}"]` : ''}`; + return node.id ? `#${CSS.escape(node.id)}` : null; } -function buildRow(name) { - const li = document.createElement('li'); - li.className = 'file staged'; - li.dataset.name = name; - - const bar = document.createElement('div'); - bar.className = 'bar'; - li.appendChild(bar); - - const row = document.createElement('div'); - row.className = 'row'; - - const label = document.createElement('span'); - label.className = 'name'; - label.textContent = name; - row.appendChild(label); - - const badge = document.createElement('span'); - badge.className = 'badge companion'; - badge.innerHTML = COMPANION_SVG; - badge.hidden = true; - row.appendChild(badge); - - const status = document.createElement('span'); - status.className = 'status'; - row.appendChild(status); - - const dl = document.createElement('a'); - dl.className = 'dl'; - dl.innerHTML = DOWNLOAD_SVG; - 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'; - rm.textContent = '×'; - rm.title = `Remove ${name}`; - rm.addEventListener('click', () => { - // A companion belongs to its base module: removing the base removes the - // companion too. - files.delete(name); - if (!name.endsWith('._')) files.delete(`${name}._`); - render(); - }); - row.appendChild(rm); - - li.appendChild(row); - - const details = document.createElement('ul'); - details.className = 'details'; - details.hidden = true; - li.appendChild(details); - - return li; -} - -function updateRow(li, name, entry) { - const isCompanion = name.endsWith('._'); - li.className = - `file ${entry.state}` + (entry.suspect && entry.state === 'ok' ? ' suspect' : ''); - - const badge = li.querySelector('.badge'); - const hasCompanion = isCompanion || files.has(`${name}._`); - badge.hidden = !hasCompanion; - if (hasCompanion) { - badge.title = isCompanion - ? 'external companion (._)' - : `companion loaded: ${name}._`; - } - - 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; - if (downloadable) { - if (dl._bytesFor !== entry.bytes) { - if (dl.href) URL.revokeObjectURL(dl.href); - dl.href = URL.createObjectURL( - new Blob([entry.bytes], { type: 'application/octet-stream' }), - ); - dl._bytesFor = entry.bytes; - } - dl.download = entry.outputName ?? outName(name); - dl.title = `Download ${dl.download}`; - } -} - -function removeRow(name, instant) { - const li = rowEls.get(name); - if (!li) return; - rowEls.delete(name); - // Release the download blob. Object URLs are roots: without this an unpacked - // 100 MB image stays resident for the life of the page every time a row is - // removed or the list is cleared. - const dl = li.querySelector('.dl'); - if (dl?.href) { - URL.revokeObjectURL(dl.href); - dl.removeAttribute('href'); - dl._bytesFor = null; - } - if (instant) { - li.remove(); - return; - } - // Fade AND collapse: without the height/margin transition the rows below - // would hold position during the fade and then snap up on removal. The - // end state must be inline too — an inline start value would otherwise - // beat the stylesheet's `.leaving { max-height: 0 }`. - li.style.maxHeight = `${li.offsetHeight}px`; - void li.offsetHeight; // reflow: give the transition a concrete start value - li.classList.add('leaving'); - li.style.maxHeight = '0px'; - setTimeout(() => li.remove(), 230); -} - -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 = []; - for (const [name] of files) { - if (name.endsWith('._') && files.has(name.slice(0, -2))) continue; - wanted.push(name); - } - const wantedSet = new Set(wanted); - - // Removals first: departed rows are marked leaving (and dropped from - // rowEls) BEFORE the ordering loop, so the loop treats them as transparent - // and never reorders siblings around them (that would snap, not slide). - for (const name of [...rowEls.keys()]) { - if (!wantedSet.has(name)) removeRow(name, false); - } - - // In-place ordering: only rows that are out of position are moved, so - // 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 slide with the collapse. - let cursor = fileList.firstChild; - for (const name of wanted) { - let li = rowEls.get(name); - if (!li) { - li = buildRow(name); - rowEls.set(name, li); - } - updateRow(li, name, files.get(name)); - while (cursor && !rowEls.has(cursor.dataset.name)) { - cursor = cursor.nextSibling; - } - if (li === cursor) { - cursor = cursor.nextSibling; - } else { - fileList.insertBefore(li, cursor); - } - } - - const unpackable = [...files].some( - ([name, e]) => - !name.endsWith('._') && - e.kind !== undefined && - !e.kind.startsWith('android-') && - e.state === 'staged', - ); - 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', () => { - files.clear(); - render(); -}); - -/** - * 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 runJob(job) { - return new Promise((resolve) => { - const w = new Worker('worker.js', { type: 'module' }); - w.onmessage = (e) => { - w.terminate(); - resolve(e.data); - }; - w.onerror = (e) => { - w.terminate(); - // 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 = [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; +/** Set a region's HTML when it changed, keeping the focus where it was. */ +function put(node, html) { + if (shown.get(node) === html) return false; + const focus = node.contains(document.activeElement) ? focusKey(document.activeElement) : null; + node.innerHTML = html; + shown.set(node, html); + if (focus) node.querySelector(focus)?.focus(); return true; } -async function unpackModule(name, entry) { - const compEntry = files.get(`${name}._`); +const listed = new WeakMap(); - 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 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 (!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.error = - `metadata already clean (v${report.version}, ${report.methods} methods) — nothing to do`; - entry.note = entry.error; +/** + * Set a list's rows, each `{ key, html }` with one element of HTML. + * + * While rows keep their places only the ones that changed are replaced, so a + * click on a row is not lost to a run that updates another row many times a + * second, and a long list is not rebuilt for one change. + */ +function putRows(node, rows) { + const before = listed.get(node); + listed.set(node, rows); + const kept = + before && + before.length <= rows.length && + node.childElementCount === before.length && + before.every((row, index) => row.key === rows[index].key); + if (!kept) { + put(node, rows.map((row) => row.html).join('')); return; } - entry.state = 'ok'; - entry.bytes = r.bytes; - entry.outputBytes = r.bytes.byteLength; - entry.outputName = outName(name); - entry.note = - `${report.remapped}/${report.methods} method tokens remapped across ${report.modules} modules`; -} - -unpackBtn.addEventListener('click', async () => { - unpackBtn.disabled = true; - clearBtn.disabled = true; - try { - for (const [name, entry] of files) { - if (name.endsWith('._') || entry.state !== 'staged') continue; - - if (entry.kind === undefined) { - entry.state = 'err'; - entry.error = 'not recognized as CrackProof-protected — skipped'; - entry.note = entry.error; - render(); - continue; - } - - // Android rows are informational only (no wasm pipeline); their staged - // 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') { - await unpackMetadata(name, entry); - } else { - await unpackModule(name, entry); - } - } catch (e) { - entry.state = 'err'; - entry.error = e instanceof Error ? e.message : String(e); - entry.note = entry.error; - } - render(); + let child = node.firstElementChild; + for (let index = 0; index < before.length; index += 1) { + const next = child.nextElementSibling; + if (before[index].html !== rows[index].html) { + const focused = child === document.activeElement; + child.insertAdjacentHTML('afterend', rows[index].html); + const fresh = child.nextElementSibling; + child.remove(); + if (focused) fresh.focus(); } - } finally { - clearBtn.disabled = false; - render(); + child = next; } -}); - -// --- 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); + if (rows.length > before.length) { + node.insertAdjacentHTML('beforeend', rows.slice(before.length).map((row) => row.html).join('')); + } + shown.delete(node); } -function generatedAt() { - return new Date().toISOString(); +const canPickFolder = () => typeof window.showDirectoryPicker === 'function'; + +let frameLanguage = null; +let detailKey = null; + +function render() { + put(el.topbar, view.topbar()); + el.main.classList.toggle('blank', state.groups.length === 0); + el.main.classList.toggle('show-detail', state.showDetail); + if (frameLanguage !== language()) { + frameLanguage = language(); + el.inputs.innerHTML = view.inputsFrame(); + el.chips = $('chips'); + el.list = $('list'); + el.search = $('search'); + el.clear = $('clear'); + el.search.value = state.search; + listed.delete(el.list); + } + el.clear.disabled = outputBusy(); + for (const control of el.settings.querySelectorAll('#set-output, [data-act="reset"]')) { + control.disabled = outputBusy(); + } + put(el.chips, view.chips()); + el.chips.hidden = el.chips.childElementCount === 0; + putRows(el.list, view.listRows()); + + // A re-render of the same view keeps its scroll position. + const key = `${state.selected}|${state.tab}`; + const top = key === detailKey ? (el.detail.querySelector('.scroll')?.scrollTop ?? 0) : 0; + if (put(el.detail, view.detail()) && top) { + const body = el.detail.querySelector('.scroll'); + if (body) body.scrollTop = top; + } + detailKey = key; + renderStatus(); + $('dragover-title').textContent = t('drag.title'); +} + +function renderStatus() { + put(el.status, view.status()); + // The button stays in the document while the line beside it is redrawn, so + // a click on it always lands. + el.cancel.hidden = state.run === null; + el.cancel.disabled = state.run?.stopping === true; + el.cancel.textContent = t('run.cancel'); +} + +let scheduled = false; + +/** Render once, after the changes of this turn. */ +function invalidate() { + if (scheduled) return; + scheduled = true; + queueMicrotask(() => { + scheduled = false; + render(); + }); +} + +onChange(invalidate); + +// The clock of a running input moves between the events that redraw the page. +setInterval(() => { + if (state.run) renderStatus(); +}, 100); + +// ---------- adding inputs ---------- + +const prober = new Prober(); +let scanChain = Promise.resolve(); +let packages = null; + +const packageModule = () => (packages ??= import('./package.js')); + +/** True for the picked-files group once it holds nothing a later file could use. */ +const isSpent = (group) => + group.kind === 'files' && group.items.length === 0 && group.companions.size === 0 && !group.scanning; + +function filesGroup() { + let group = state.groups.find((candidate) => candidate.kind === 'files'); + if (!group) { + group = makeGroup('files', ''); + state.groups.unshift(group); + } + return group; +} + +/** Where a module's header starts; a companion begins with a copy of it. */ +const HEADER_OFFSET = 4096; +const HEADER_PROBE = 32; + +/** + * What the `._` file beside a module is to it: `{ state, name }`, with `state` + * one of `absent`, `spliced`, `unmatched`, `unreadable`. A companion is this + * module's payload when it starts with the module's own `header` bytes. + */ +async function companionOf(group, path, header) { + const name = `${baseName(path)}._`; + const open = group.companions.get(`${path}._`); + if (!open) return { state: 'absent', name }; + try { + const file = await open(); + const head = new Uint8Array(await file.slice(0, HEADER_PROBE).arrayBuffer()); + const same = + head.length === HEADER_PROBE && + header.length === HEADER_PROBE && + head.every((byte, index) => byte === header[index]); + return { state: same ? 'spliced' : 'unmatched', name }; + } catch { + return { state: 'unreadable', name }; + } } /** - * 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. + * Decide what one file is. + * + * Returns `{ item }` for an input to list, `{ skipped: true }` for a file that + * was probed and is not a target, and `{}` for one too small to probe. A file + * the user picked is always listed, and is told by what it holds whatever its + * name; a file a folder scan found is listed only when it is a target. */ -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, - })), +async function classify(group, candidate, file, explicit) { + const item = makeItem(group, candidate, file.size); + // A file that is no target is known by its name and size alone. + const plain = () => { + item.kind = null; + item.notProtected = true; + return explicit ? { item } : { skipped: true }; + }; + if (file.size < MIN_SIZE && !explicit) return {}; + + const prefix = new Uint8Array(await file.slice(0, PREFIX_SIZE).arrayBuffer()); + const magic = sniff(prefix); + const named = (kind) => explicit || candidate.kind === kind; + + if (magic.zip && candidate.kind === 'package') { + // Every app package is listed; what it holds is known once it has run. + item.kind = 'package'; + item.entries = []; + const { inventory, UnsafeEntry } = await packageModule(); + try { + item.container = await inventory( + file, + candidate.path, + (bytes, truncated) => prober.manifest(bytes, truncated), + { maxNestedBytes: state.limitBytes * 4 }, + ); + item.entries = makeEntries(item); + } catch (error) { + item.identityError = error instanceof UnsafeEntry + ? await prober.unsafeEntry(shownPath(fullPath(item)), language()) + : pageError('web.read_failed', null, error?.message ?? error); + } + return { item }; + } + if (magic.metadata && named('metadata')) { + item.kind = 'metadata'; + item.pre = (await prober.prefix(prefix)).profile; + item.metadataVersion = prefix.length >= 8 ? new DataView(prefix.buffer).getUint32(4, true) : null; + return { item }; + } + if (magic.mz && named('pe')) { + const reply = await prober.prefix(prefix); + item.kind = 'pe'; + item.pre = reply.profile; + item.peKind = reply.kind; + item.header = prefix.slice(HEADER_OFFSET, HEADER_OFFSET + HEADER_PROBE); + item.companion = await companionOf(group, candidate.path, item.header); + if (reply.kind) return { item }; + // A module without the protection keeps what its header says it is. + item.notProtected = true; + return explicit ? { item } : { skipped: true }; + } + if (magic.elf64Aarch64 && named('so')) { + item.kind = 'so'; + // A library over the limit is not read here; it stays a candidate. + if (file.size > state.limitBytes) return { item }; + item.pre = await prober.library(file, file.size); + if (item.pre?.recognition !== 'not_recognized') return { item }; + item.pre = null; + } + return plain(); +} + +/** The identity of a picked file, by which the same file is not listed twice. */ +const fileKey = (file) => `${file.name}|${file.size}|${file.lastModified}`; + +async function runScan(scan, candidates, source) { + const { group } = scan; + const { signal } = scan.controller; + let list = candidates; + if (!list) { + const walk = source.walk(() => { + group.stats.walkErrors += 1; + }); + const found = await collect(walk, signal); + list = found.candidates; + for (const [path, open] of found.companions) group.companions.set(path, open); + } + let first = true; + for (const candidate of list) { + if (signal.aborted) return; + let item = null; + try { + const file = await candidate.open(); + const outcome = await classify(group, candidate, file, source.explicit); + if (signal.aborted) return; + item = outcome.item ?? null; + if (outcome.skipped) group.stats.skipped += 1; + } catch (error) { + if (signal.aborted) return; + if (source.explicit) { + // A picked file that cannot be examined is still listed, with why. + item = makeItem(group, candidate, 0); + item.identityError = pageError('web.read_failed', null, error?.message ?? error); + } else { + group.stats.probeErrors += 1; + } + } + if (item) { + item.fileKey = candidate.key ?? null; + group.items.push(item); + group.found += 1; + // Added files show the first of them, unless an input is already shown. + if (first && source.explicit && !find(state.selected)?.item) { + state.selected = item.id; + state.multi = []; + } + first = false; + } + invalidate(); + } +} + +function startScan(group, candidates, source) { + const scan = { group, controller: new AbortController() }; + state.scans.push(scan); + group.scanning = true; + if (!source.explicit) { + // An added folder is shown at once, while its scan runs. + state.selected = group.id; + state.multi = []; + } + state.notice = null; + invalidate(); + scanChain = scanChain + .then(() => runScan(scan, candidates, source)) + .catch((error) => console.error(error)) + .then(() => { + state.scans = state.scans.filter((other) => other !== scan); + group.scanning = state.scans.some((other) => other.group === group); + // The probe worker is not kept between scans. + if (state.scans.length === 0) prober.close(); + if (isSpent(group)) dropGroup(group); + invalidate(); + }); +} + +/** Look again at the companions of modules that were added before them. */ +async function repair(group, names) { + for (const item of group.items) { + if (item.kind !== 'pe' || !item.header || !names.has(`${item.relPath}._`)) continue; + item.companion = await companionOf(group, item.relPath, item.header); + } + invalidate(); +} + +function addFiles(files) { + if (files.length === 0) return; + const group = filesGroup(); + const known = new Set(group.items.map((item) => item.fileKey)); + const candidates = []; + const companions = new Set(); + for (const file of files) { + const open = async () => file; + if (isCompanionName(file.name)) { + group.companions.set(file.name, open); + companions.add(file.name); + } else if (!known.has(fileKey(file))) { + known.add(fileKey(file)); + candidates.push({ path: file.name, kind: candidateKind(file.name), open, key: fileKey(file) }); + } + } + if (companions.size) repair(group, companions); + startScan(group, candidates, { explicit: true }); +} + +function addFolder(name, walk, handle = null) { + const group = makeGroup('folder', name || '/', handle); + state.groups.push(group); + startScan(group, null, { explicit: false, walk }); +} + +/** The group of a folder that was dropped before, when the browser can tell. */ +async function sameFolder(handle) { + for (const group of state.groups) { + if (group.handle && (await group.handle.isSameEntry(handle).catch(() => false))) return group; + } + return null; +} + +/** What a drop holds. Called inside the drop handler, where the items are live. */ +function takeDrop(transfer) { + return [...(transfer?.items ?? [])] + .filter((item) => item.kind === 'file') + .map((item) => ({ + handle: item.getAsFileSystemHandle ? item.getAsFileSystemHandle().catch(() => null) : null, + entry: item.webkitGetAsEntry?.() ?? null, + file: item.getAsFile(), + })); +} + +async function addDropped(taken) { + const files = []; + for (const { handle, entry, file } of taken) { + if (entry?.isDirectory) { + // The entry lists the folder: see `scan.js`. The handle, where the + // browser gives one, only tells whether two folders are the same. + const dropped = handle ? await handle : null; + const directory = dropped?.kind === 'directory' ? dropped : null; + const again = directory ? await sameFolder(directory) : null; + if (again) select(again.id); + else addFolder(entry.name, (onError) => walkEntry(entry, onError), directory); + } else if (file) { + files.push(file); + } + } + addFiles(files); +} + +// ---------- removing inputs ---------- + +function dropGroup(group) { + for (const scan of state.scans) if (scan.group === group) scan.controller.abort(); + state.groups = state.groups.filter((other) => other !== group); +} + +/** Drop what the selection held of rows that are gone. */ +function forget() { + state.multi = state.multi.filter((id) => find(id)); + if (state.selected && !find(state.selected)) { + state.selected = null; + state.showDetail = false; + } +} + +/** Remove the group, or the input, with `id`. An entry stands for its package. */ +function remove(id) { + const current = id && find(id); + if (!current || outputBusy()) return; + if (current.group) { + dropGroup(current.group); + } else { + const item = current.item.parent ?? current.item; + const group = item.group; + group.items = group.items.filter((other) => other !== item); + if (isSpent(group)) dropGroup(group); + } + forget(); + invalidate(); +} + +function clearAll() { + if (outputBusy()) return; + for (const group of [...state.groups]) dropGroup(group); + state.contexts.clear(); + state.unfolded.clear(); + state.selected = null; + state.multi = []; + state.showDetail = false; + state.filter = 'all'; + state.search = ''; + if (el.search) el.search.value = ''; + state.tab = 'overview'; + state.notice = null; + invalidate(); +} + +// ---------- handing results back ---------- + +function download(blob, name) { + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = name; + document.body.append(link); + link.click(); + link.remove(); + setTimeout(() => URL.revokeObjectURL(url), 60_000); +} + +async function downloadAll() { + const archive = await downloadArchive(allItems()); + if (archive) download(archive.blob, archive.name); +} + +/** The inputs an export covers and the name it goes by: the selection's. */ +function exportScope() { + const current = state.selected && find(state.selected); + const item = current?.item ? (current.item.parent ?? current.item) : null; + const items = item ? [item] : current?.group ? current.group.items : allItems(); + const name = item ? item.name : current?.group?.kind === 'folder' ? current.group.name : null; + return { items, name }; +} + +function exportReport() { + const { items, name } = exportScope(); + const generatedAt = new Date().toISOString(); + const report = buildReport(items, { generatedAt, version: VERSION, limitBytes: state.limitBytes }); + download( + new Blob([serializeReport(report)], { type: 'application/json' }), + reportFileName(name, generatedAt), ); } -exportBtn.addEventListener('click', () => { - const at = generatedAt(); - downloadJson( - reportFileName(null, at), - serializeReport(buildReport(files, { generatedAt: at, limitBytes, includeNotes: true })), +async function exportText() { + const { items, name } = exportScope(); + const { reportText } = await import('./text.js'); + download( + new Blob([reportText(items)], { type: 'text/plain;charset=utf-8' }), + reportFileName(name, new Date().toISOString(), 'txt'), ); +} + +/** Ask for the folder outputs are written to. Resolves to whether one was chosen. */ +async function chooseOutputFolder() { + if (outputBusy()) return false; + let dir; + try { + dir = await window.showDirectoryPicker({ mode: 'readwrite' }); + } catch { + return false; + } + if (outputBusy()) return false; + state.out = { mode: 'folder', dir }; + invalidate(); + // Results that are already here are written too, wherever they went before. + await saveAll(allItems(), true); + return true; +} + +function setOutput(mode) { + if (outputBusy()) return; + state.out = { ...state.out, mode }; + invalidate(); + if (mode === 'folder') saveAll(allItems(), false); +} + +async function copyText(text, button) { + try { + await navigator.clipboard.writeText(text); + } catch { + return; + } + if (!button) return; + const label = button.textContent; + button.textContent = '✓'; + setTimeout(() => { + if (button.isConnected) button.textContent = label; + }, 900); +} + +// ---------- menus and dialogs ---------- + +function closeMenu() { + el.menu.innerHTML = ''; +} + +function openMenu(html, x, y) { + el.menu.innerHTML = ``; + const box = el.menu.firstElementChild; + const { width, height } = box.getBoundingClientRect(); + box.style.left = `${Math.max(8, Math.min(x, window.innerWidth - width - 8))}px`; + box.style.top = `${Math.max(8, Math.min(y, window.innerHeight - height - 8))}px`; + box.querySelector('button:not(:disabled)')?.focus(); +} + +function showDialog(dialog) { + if (dialog.open) return; + dialog.classList.add('opening'); + dialog.showModal(); + // Commit the transparent starting state after the dialog enters the top + // layer. This also works in browsers without CSS @starting-style. + dialog.getBoundingClientRect(); + dialog.classList.remove('opening'); +} + +function openLegal() { + el.legal.innerHTML = view.legal(accepted); + showDialog(el.legal); +} + +function drawSettings() { + el.settings.innerHTML = view.settings(canPickFolder()); +} + +function openSettings() { + drawSettings(); + showDialog(el.settings); +} + +/** Keep the backdrop modal until its fade finishes, then let the browser restore focus. */ +async function closeDialog(dialog) { + if (!dialog.open || dialog.inert) return false; + dialog.inert = true; + const fade = dialog.getAnimations().find((animation) => animation.transitionProperty === 'opacity'); + if (fade) await fade.finished.catch(() => {}); + dialog.close(); + dialog.inert = false; + return true; +} + +async function setLanguage(tag, remember = true) { + await loadLanguage(tag); + if (remember) store(STORE.language, language()); + document.title = 'Senbei'; + if (el.legal.open) el.legal.innerHTML = view.legal(accepted); + if (el.settings.open) drawSettings(); + closeMenu(); + render(); +} + +/** + * Show the row with `id`. With `toggle`, as with Ctrl or Cmd held, the row + * joins or leaves the rows a run takes; a group is never one of those. + */ +function select(id, toggle = false) { + const current = find(id); + if (!current) return; + if (toggle && !current.group) { + const shownNow = state.selected; + if (shownNow && !state.multi.includes(shownNow) && find(shownNow)?.item) state.multi.push(shownNow); + const at = state.multi.indexOf(id); + if (at >= 0) state.multi.splice(at, 1); + else state.multi.push(id); + } else { + state.multi = []; + } + state.selected = id; + state.showDetail = true; + invalidate(); +} + +/** True while inputs cannot be run or removed. */ +const busy = () => outputBusy() || state.scans.length > 0; + +const actions = { + 'add-files': () => el.pickFiles.click(), + 'add-folder': () => el.pickFolder.click(), + run: () => startRun(targets()), + 'run-item': (node) => { + closeMenu(); + const item = find(node.dataset.id)?.item; + if (item) startRun([item.parent ?? item]); + }, + cancel: cancelRun, + select: (node, event) => select(node.dataset.id, el.list.contains(node) && (event.ctrlKey || event.metaKey)), + toggle: (node) => { + const id = node.dataset.id; + if (!state.collapsed.delete(id)) state.collapsed.add(id); + invalidate(); + }, + 'show-entries': (node) => { + state.multi = []; + state.selected = node.dataset.id; + state.tab = 'entries'; + state.showNonTargets = true; + state.showDetail = true; + invalidate(); + }, + filter: (node) => { + state.filter = node.dataset.filter; + invalidate(); + }, + tab: (node) => { + state.tab = node.dataset.tab; + invalidate(); + }, + loglevel: (node) => { + state.logLevel = node.dataset.level; + invalidate(); + }, + back: () => { + state.showDetail = false; + invalidate(); + }, + copy: (node) => copyText(node.dataset.text, node), + 'copy-log': (node) => copyText(view.logText(), node), + 'copy-path': (node) => { + closeMenu(); + const item = find(node.dataset.id)?.item; + if (item) copyText(shownPath(fullPath(item))); + }, + download: (node) => { + const output = find(node.dataset.id)?.item?.result?.outputs[Number(node.dataset.n)]; + if (output) download(output.blob, baseName(output.path)); + }, + 'download-all': () => downloadAll(), + export: exportReport, + 'export-text': () => exportText(), + remove: (node) => { + closeMenu(); + remove(node.dataset.id); + }, + clear: clearAll, + 'out-menu': (node) => { + const box = node.getBoundingClientRect(); + openMenu(view.outMenu(canPickFolder()), box.right - 330, box.bottom + 4); + }, + 'out-downloads': () => { + closeMenu(); + setOutput('downloads'); + }, + 'out-folder': () => { + closeMenu(); + setOutput('folder'); + }, + 'out-choose': () => { + closeMenu(); + chooseOutputFolder(); + }, + settings: openSettings, + 'settings-tab': (node) => { + state.settingsTab = node.dataset.tab; + drawSettings(); + }, + 'close-settings': () => closeDialog(el.settings), + 'show-legal': async () => { + if (await closeDialog(el.settings)) openLegal(); + }, + 'close-legal': () => closeDialog(el.legal), + accept: () => { + accepted = true; + store(STORE.legal, '1'); + closeDialog(el.legal); + warmUp(); + }, + reset: async () => { + if (outputBusy()) return; + store(STORE.language, null); + store(STORE.limit, null); + state.limitBytes = DEFAULT_LIMIT_MIB * 1024 * 1024; + state.out = { mode: 'downloads', dir: null }; + await setLanguage(languageFor(navigator.languages), false); + }, +}; + +const changes = { + language: (node) => setLanguage(node.value), + limit: (node) => { + state.limitBytes = parseLimitMiB(node.value, state.limitBytes); + store(STORE.limit, String(Math.round(state.limitBytes / (1024 * 1024)))); + drawSettings(); + }, + output: async (node) => { + if (node.value === 'choose') await chooseOutputFolder(); + else setOutput(node.value); + if (el.settings.open) drawSettings(); + }, + 'non-targets': (node) => { + state.showNonTargets = node.checked; + invalidate(); + }, +}; + +// ---------- events ---------- + +document.addEventListener('click', (event) => { + // A folded part stays as it was left when its view is drawn again: the + // click is about to open or close it. + const folded = event.target.closest?.('details[data-fold] > summary')?.parentElement; + if (folded?.open) state.unfolded.delete(folded.dataset.fold); + else if (folded) state.unfolded.add(folded.dataset.fold); + const node = event.target.closest?.('[data-act]'); + if (!el.menu.contains(event.target) && node?.dataset.act !== 'out-menu') closeMenu(); + if (!node || node.disabled) return; + actions[node.dataset.act]?.(node, event); }); -// Paint the initial state so the limit hint and the action row are consistent -// before anything is staged. -render(); +document.addEventListener('change', (event) => { + const node = event.target.closest?.('[data-change]'); + if (node) changes[node.dataset.change]?.(node); +}); + +document.addEventListener('input', (event) => { + if (event.target.id !== 'search') return; + state.search = event.target.value; + invalidate(); +}); + +const typing = (event) => Boolean(event.target.closest?.('input, select, textarea')); + +document.addEventListener('keydown', (event) => { + if (event.key === 'Escape') { + closeMenu(); + return; + } + if (!accepted || el.legal.open || el.settings.open) return; + if ((event.ctrlKey || event.metaKey) && !event.altKey && event.key.toLowerCase() === 'o') { + event.preventDefault(); + el.pickFiles.click(); + return; + } + if (event.key === 'Delete' && !typing(event) && !busy()) { + // The key removes an input, never a whole group. + const item = state.selected && find(state.selected)?.item; + if (item && !item.isEntry) remove(item.id); + return; + } + const node = event.target.closest?.('[tabindex][data-act]'); + if (!node) return; + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + node.click(); + } else if ((event.key === 'ArrowDown' || event.key === 'ArrowUp') && el.list?.contains(node)) { + event.preventDefault(); + const rows = [...el.list.querySelectorAll('[data-act="select"]')]; + const next = rows[rows.indexOf(node) + (event.key === 'ArrowDown' ? 1 : -1)]; + if (next) { + next.focus(); + // Moving through the list selects without leaving it on a narrow window. + state.selected = next.dataset.id; + state.multi = []; + invalidate(); + } + } +}); + +document.addEventListener('contextmenu', (event) => { + const node = event.target.closest?.('#list [data-act="select"]'); + if (!node) return; + event.preventDefault(); + const id = node.dataset.id; + const current = find(id); + if (!current) return; + const item = current.item; + const options = { + kind: current.group ? 'group' : item.isEntry ? 'entry' : 'item', + runnable: Boolean(item) && (item.isEntry || !item.notProtected) && !isBusy(item.parent ?? item), + busy: busy(), + }; + openMenu(view.rowMenu(id, options), event.clientX, event.clientY); +}); + +window.addEventListener('resize', closeMenu); + +el.pickFiles.addEventListener('change', () => { + const files = [...el.pickFiles.files]; + el.pickFiles.value = ''; + addFiles(files); +}); + +el.pickFolder.addEventListener('change', () => { + const files = [...el.pickFolder.files]; + el.pickFolder.value = ''; + if (files.length === 0) return; + // A browser that cannot pick a folder hands over plain files instead. + if (files.some((file) => file.webkitRelativePath)) addFolder(fileListRoot(files), () => walkFileList(files)); + else addFiles(files); +}); + +// Route Escape through the fade; the first-use notice still requires acceptance. +for (const dialog of [el.settings, el.legal]) { + dialog.addEventListener('cancel', (event) => { + event.preventDefault(); + if (dialog !== el.legal || accepted) closeDialog(dialog); + }); +} + +let dragDepth = 0; +const hasFiles = (event) => [...(event.dataTransfer?.types ?? [])].includes('Files'); +const canDrop = () => accepted && !el.settings.open && !el.legal.open; + +window.addEventListener('dragenter', (event) => { + if (!canDrop() || !hasFiles(event)) return; + event.preventDefault(); + dragDepth += 1; + el.dragover.hidden = false; +}); +window.addEventListener('dragover', (event) => { + if (canDrop() && hasFiles(event)) event.preventDefault(); +}); +window.addEventListener('dragleave', () => { + dragDepth = Math.max(0, dragDepth - 1); + if (dragDepth === 0) el.dragover.hidden = true; +}); +window.addEventListener('drop', (event) => { + dragDepth = 0; + el.dragover.hidden = true; + if (!hasFiles(event)) return; + event.preventDefault(); + if (canDrop()) addDropped(takeDrop(event.dataTransfer)); +}); + +window.addEventListener('beforeunload', (event) => { + // Results live in this tab only. + if (state.run || allOutputs().length) { + event.preventDefault(); + event.returnValue = ''; + } +}); + +// ---------- start ---------- + +/** Fetch and compile the engine while the page is idle, before it is needed. */ +function warmUp() { + const start = () => loadEngine().catch(() => {}); + if (window.requestIdleCallback) requestIdleCallback(start, { timeout: 3000 }); + else setTimeout(start, 300); +} + +async function start() { + state.limitBytes = parseLimitMiB(stored(STORE.limit)); + const wanted = stored(STORE.language); + const known = LANGUAGES.some(([code]) => code === wanted); + await setLanguage(known ? wanted : languageFor(navigator.languages), false); + if (accepted) warmUp(); + else openLegal(); +} + +start(); diff --git a/web/assets/Asul-Bold.woff2 b/web/assets/Asul-Bold.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..0a4d696d749ee4d7600e5c84f3dfbc1b18fed952 GIT binary patch literal 13396 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 q59vya3elxYACvi9`5# diff --git a/web/assets/icon-128.png b/web/assets/icon-128.png new file mode 100644 index 0000000000000000000000000000000000000000..72c351c558ef147bcc34b8739e61e1f4877ea2ec GIT binary patch literal 17521 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

    q{M;OG@CXRDgHH%x@v|`~v}(oRy}-AS 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 M07*qoM6N<$g22PPCjbBd literal 0 HcmV?d00001 diff --git a/web/assets/icon-32.png b/web/assets/icon-32.png new file mode 100644 index 0000000000000000000000000000000000000000..8b74d6c873de00f183b01689f2310bf57e31064e GIT binary patch literal 2293 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 P00000NkvXXu0mjf+a7Fw literal 0 HcmV?d00001 diff --git a/web/detail.js b/web/detail.js new file mode 100644 index 0000000..0c94a40 --- /dev/null +++ b/web/detail.js @@ -0,0 +1,852 @@ +// The detail pane: what the selected group, input, or entry is, and what its +// last run found. Every function returns HTML from the state alone. + +import { show, t, tv } from './i18n.js'; +import { + counts, + find, + fullPath, + isBusy, + isDone, + isNonTarget, + outcomeOf, + state, + targetEntries, + timeOf, +} from './state.js'; +import { baseName, candidateKind, dirName, formatBytes, formatCount, formatDuration, localClock } from './model.js'; +import { messagePlan, ranAsModule, stagesOf } from './report.js'; +import { + card, + dot, + esc, + faint, + fold, + formatLabel, + grid, + groupName, + hash, + kv, + messages, + modeLabel, + mono, + note, + pill, + routeOf, + rowState, + shownPath, + statePill, + stepText, + stepTitle, + tag, + typeTag, +} from './ui.js'; + +// ---------- shell ---------- + +const TAB_LABEL = { overview: 'tab.overview', entries: 'tab.entries', log: 'tab.log' }; + +/** The tab a view with `tabs` shows: the chosen one, or its first. */ +const activeTab = (tabs) => (tabs.includes(state.tab) ? state.tab : tabs[0]); + +/** + * The head of a detail view: title row, path line, and tabs. `badge` gives a + * count to show beside a tab; `exports` adds the export buttons. + */ +function head({ title, tagText = '', pills = '', path = '', tabs = [], badge = {}, exports = false }) { + const shown = activeTab(tabs); + const tab = (key) => { + const count = badge[key] == null ? '' : `${badge[key]}`; + return ( + `` + ); + }; + const actions = exports + ? `` + + `` + : ''; + return ( + `

    ` + + `` + + `

    ${esc(title)}

    ${tagText ? tag(tagText) : ''}${pills}` + + `${actions}
    ` + + `${path ? `
    ${esc(path)}
    ` : ''}` + + `${tabs.length ? `
    ${tabs.map(tab).join('')}
    ` : ''}
    ` + ); +} + +/** + * The body under a head, on the panel colour. A padded body scrolls as a + * whole; the other kind lays out its own parts, one of which scrolls. + */ +const body = (html, padded = true) => + padded ? `
    ${html}
    ` : `
    ${html}
    `; + +/** + * A table. Each column is `[label, width]`, with `'num'` as a third member + * for right-aligned numbers; the one column without a width takes what the + * others leave. `tall` rows have room for two lines. + */ +function table(columns, rows, tall = false) { + // Columns are 8 apart: half of the gap is on each side of a cell, and the + // table's two edges have none. + const GAP = 8; + const last = columns.length - 1; + const outer = (width, index) => width + (index === 0 || index === last ? GAP / 2 : GAP); + const grow = columns.findIndex(([, width]) => width == null); + const fixed = columns.reduce((sum, [, width], index) => sum + (width == null ? 0 : outer(width, index)), 0); + const cols = columns.map(([, width], index) => + width == null ? '' : ``, + ); + const heads = columns.map( + ([label, , kind]) => `${esc(label)}`, + ); + return ( + `
    ` + + `${cols.join('')}${heads.join('')}` + + `${rows.join('')}
    ` + ); +} + +const toned = (value, tone) => `${esc(value)}`; + +/** A count that takes its tone only when it is not zero. */ +const countText = (count, tone) => (count > 0 ? toned(count, tone) : String(count)); + +/** A count with thousands separators, as HTML. */ +const counted = (value) => esc(formatCount(value)); + +// ---------- log ---------- + +const LEVEL_LABEL = { info: 'log.lv_info', step: 'log.lv_step', warn: 'log.lv_warn', error: 'log.lv_error' }; +const LEVEL_TONE = { info: 'c-skip', step: 'c-info', warn: 'c-warn', error: 'c-err' }; +const LOG_LEVELS = [ + ['all', 'log.f_all'], + ['nosteps', 'log.f_nosteps'], + ['problems', 'log.f_problems'], +]; + +function stageText(line) { + let text = `${tv('stage', line.stage)}: ${tv('stageStatus', line.status)}`; + if (line.durationMs > 0) text += ` (${formatDuration(line.durationMs)})`; + const detail = line.detail ? show(line.detail, line.lang) : ''; + return detail ? `${text} — ${detail}` : text; +} + +/** The text of one log line, in the page language. */ +export function lineText(line) { + switch (line.type) { + case 'run-started': + return t('LogRunStarted', { mode: t('tb.unpack'), n: line.n }); + case 'scan': + return t('LogScan', { n: line.n, s: line.s }); + case 'scan-incomplete': + return t('batch.scan_incomplete'); + case 'input-started': + return t('LogInputStarted', { i: line.i, n: line.n, p: line.path }); + case 'companion': + return t('LogCompanion', { p: line.name }); + case 'step': { + const title = stepTitle(line); + return line.i == null ? title : t('LogStep', { i: line.i, n: line.of, s: title }); + } + case 'stage': + return stageText(line); + case 'message': + return show(line.message, line.lang); + case 'entry': + return t('LogEntry', { p: line.path, o: t(line.outcome) }); + case 'finished': + return t('LogInputFinished', { o: t(line.outcome), t: formatDuration(line.durationMs) }); + case 'summary': + return t('LogSummary', line.counts); + default: + return line.text ?? ''; + } +} + +function keep(line) { + if (state.logLevel === 'nosteps') return line.level !== 'step' && line.level !== 'detail'; + if (state.logLevel === 'problems') return line.level === 'warn' || line.level === 'error'; + return true; +} + +const levelLabel = (line) => (LEVEL_LABEL[line.level] ? t(LEVEL_LABEL[line.level]) : ''); + +/** Log lines without a bar of their own. `scrolls` gives them their own scroll. */ +function logBox(lines, scrolls = false) { + const rows = lines.filter(keep).map( + (line) => + `
    ${localClock(line.at)}` + + `${esc(levelLabel(line))}` + + `${esc(lineText(line))}
    `, + ); + return `
    ${rows.join('')}
    `; +} + +/** The log tab: a filter bar and the lines below it. */ +function logTab(lines) { + const levels = LOG_LEVELS.map( + ([key, label]) => + ``, + ); + return ( + `
    ${levels.join('')}
    ` + + `
    ${logBox(lines, true)}` + ); +} + +/** The log the selection has: a group's last run, or an input's. */ +function selectedLog() { + const current = state.selected && find(state.selected); + if (current?.group) return current.group.lastRun?.log ?? []; + return current?.item?.log ?? []; +} + +/** Log lines as plain text, independent of what's selected or filtered. */ +export function formatLog(lines) { + return lines.map((line) => `${localClock(line.at)} ${levelLabel(line).padEnd(6)} ${lineText(line)}\n`).join(''); +} + +/** The visible log as plain text, for the clipboard. */ +export function logText() { + return formatLog(selectedLog().filter(keep)); +} + +// ---------- stages ---------- + +const STAGE_ICON = { ok: ['✓', 'ok'], skipped: ['–', 'skip'], failed: ['✕', 'err'], blocked: ['⏸', 'warn'] }; +const ARROW = '→'; + +function stageChip({ icon = '', tone = 'skip', name, duration = '', status = '', detail = '', dimmed = false }) { + return ( + `
    ` + + `${icon ? `${icon}` : ''}${esc(name)}` + + `${duration ? `${esc(duration)}` : ''}
    ` + + `${status ? `
    ${esc(status)}
    ` : ''}` + + `${detail ? `
    ${esc(detail)}
    ` : ''}
    ` + ); +} + +/** The stages of a finished input. `shown` holds the messages already on the page. */ +function stagesCard(item, shown) { + const stages = stagesOf(item); + if (stages.length === 0) return ''; + const lang = item.result?.lang; + const chips = stages.map((stage) => { + const [icon, tone] = STAGE_ICON[stage.status]; + // A path is in the identity card, and a message the page shows is above. + const hidden = !stage.detail || stage.detail.path || shown.has(stage.detail.text); + return stageChip({ + icon, + tone, + name: tv('stage', stage.stage), + duration: stage.durationMs > 0 ? formatDuration(stage.durationMs) : '', + status: tv('stageStatus', stage.status), + detail: hidden ? '' : show(stage.detail, lang), + }); + }); + return card(t('ov.stages'), `
    ${chips.join(ARROW)}
    `, { wide: true }); +} + +/** The stages of a running input: where it is, and what is still to come. */ +function progressCard(step) { + const detected = Boolean(step); + const chips = [ + stageChip({ + icon: detected ? '✓' : '●', + tone: detected ? 'ok' : 'info', + name: tv('stage', 'detection'), + status: detected ? tv('stageStatus', 'ok') : t('run.running'), + }), + stageChip({ icon: '●', tone: 'info', name: tv('stage', 'recovery'), status: stepText(step), dimmed: !detected }), + stageChip({ name: tv('stage', 'static_validation'), dimmed: true }), + stageChip({ name: tv('stage', 'output_write'), dimmed: true }), + ]; + return card(t('run.progress'), `
    ${chips.join(ARROW)}
    `, { wide: true }); +} + +// ---------- groups ---------- + +const groupPath = (group) => (group.kind === 'folder' ? shownPath(`${group.name}/`) : ''); + +function groupTable(group) { + const rows = group.items.map((item) => { + // The same state the inputs pane shows for this row. + const row = rowState(item); + let route = ''; + if (isDone(item)) { + // A package that could not be listed has no targets to count. + route = item.kind === 'package' && item.container + ? t('EntriesSummary', { n: targetEntries(item).length }) + : (routeOf(item) ?? '—'); + } + return ( + `${dot(row.dot)}` + + `${esc(item.name)}${tag(typeTag(item))}` + + `${esc(row.label)}` + + `${esc(route)}${esc(row.time ?? '')}` + ); + }); + const columns = [ + ['', 18], + [t('col.name')], + [t('col.type'), 130], + [t('col.outcome'), 130], + [t('col.route'), 210], + [t('col.time'), 80, 'num'], + ]; + return table(columns, rows); +} + +function scanningDetail(group) { + const scan = card( + t('batch.scan'), + kv([[t('scan.found'), String(group.found)]]) + note(t('batch.scan_note')), + { wide: true }, + ); + return ( + head({ title: groupName(group), pills: pill('info', t('scan.running')), path: groupPath(group) }) + + body(grid([scan])) + ); +} + +function groupDetail(group) { + if (group.scanning) return scanningDetail(group); + const run = group.lastRun; + const hasResults = group.items.some(isDone); + const pills = run?.running ? pill('info', t('run.running')) : run ? pill('info', modeLabel()) : ''; + const tabs = ['overview', 'log']; + const top = head({ title: groupName(group), pills, path: groupPath(group), tabs, exports: hasResults }); + if (activeTab(tabs) === 'log') return top + body(logTab(run?.log ?? []), false); + + const count = counts(group.items); + const spent = group.items.reduce((sum, item) => sum + (isDone(item) ? (timeOf(item) ?? 0) : 0), 0); + const duration = run?.durationMs > 0 ? run.durationMs : spent; + const { stats } = group; + const incomplete = stats.walkErrors + stats.probeErrors > 0; + const cards = []; + if (incomplete) { + const blocks = [{ tone: 'warn', message: { key: 'batch.scan_incomplete' } }]; + cards.push(card(t('ov.messages'), messages(blocks), { wide: true })); + } + cards.push( + card( + t('batch.summary'), + kv([ + [t('batch.inputs'), String(count.all)], + [t('filter.ok'), toned(count.ok, 'ok')], + [t('filter.suspect'), countText(count.suspect, 'warn')], + [t('filter.failed'), countText(count.failed, 'err')], + [t('filter.skipped'), String(count.skipped)], + ]), + // Nothing has run yet: no time to show. + { aside: hasResults || duration > 0 ? esc(formatDuration(duration)) : '' }, + ), + ); + if (group.kind === 'folder') { + cards.push( + card( + t('batch.scan'), + kv([ + [t('batch.non_target'), String(stats.skipped)], + [t('batch.walk_errors'), countText(stats.walkErrors, 'warn')], + [t('batch.probe_errors'), countText(stats.probeErrors, 'warn')], + ]) + note(t('batch.scan_note')), + ), + ); + } + cards.push(card(t('batch.inputs'), groupTable(group), { wide: true })); + return top + body(grid(cards)); +} + +// ---------- inputs not yet run ---------- + +/** Lines stacked in one value cell. */ +const stack = (lines) => `
    ${lines.filter(Boolean).map((line) => `
    ${line}
    `).join('')}
    `; + +function companionRow(item) { + const companion = item.companion; + if (!companion || companion.state === 'absent') return null; + const state = companion.state === 'spliced' ? t('companion.paired') : tv('companion', companion.state); + return [t('ov.companion'), `${esc(state)}·${mono(companion.name)}`]; +} + +/** What a light look at a file found, before anything ran. */ +function identifiedRows(item) { + const size = [t('ov.source'), esc(formatBytes(item.size))]; + if (item.identityError) return item.size ? [size] : []; + switch (item.kind) { + case 'package': { + const container = item.container; + const named = container.archives.find((archive) => archive.identity); + return [ + [t('pkg.kind'), esc(container.kind.toUpperCase())], + named && [t('pkg.package'), `${mono(named.identity[0])}${faint(named.identity[1])}`], + [t('pkg.entries'), counted(container.archives[0].entryCount)], + [t('pkg.candidates'), counted(item.entries.length)], + ]; + } + case 'pe': { + const observed = item.pre?.observed; + return [ + [t('ov.platform'), esc(tv('platform', observed?.platform ?? 'windows_pe'))], + [t('ov.format'), mono(formatLabel(observed?.format))], + observed?.kind && [t('ov.kind'), esc(tv('kind', observed.kind))], + size, + companionRow(item), + ]; + } + case 'metadata': + return [ + [t('ov.platform'), esc(tv('platform', 'il2cpp_metadata'))], + item.metadataVersion != null && [t('ov.metadata_version'), esc(item.metadataVersion)], + size, + ]; + case 'so': + return [ + [t('ov.platform'), esc(tv('platform', 'android_elf'))], + [t('ov.format'), mono(formatLabel('elf64_aarch64'))], + size, + ]; + default: + return [size]; + } +} + +function actionsCard(item) { + const blocked = item.notProtected || state.run !== null || state.scans.length > 0; + return card( + t('pending.next'), + `
    ` + + `${esc(t('web.unpack_desc'))}
    ` + + (item.notProtected ? note(t('pending.not_protected_note')) : ''), + ); +} + +function pendingDetail(item) { + const top = head({ + title: item.name, + tagText: typeTag(item), + pills: statePill(item), + path: shownPath(fullPath(item)), + tabs: ['overview'], + }); + const cards = []; + if (item.identityError) { + const blocks = [{ tone: 'err', message: item.identityError }]; + cards.push(card(t('ov.messages'), messages(blocks), { wide: true })); + } + cards.push(card(t('pending.identified'), kv(identifiedRows(item))), actionsCard(item)); + return top + body(grid(cards)); +} + +// ---------- running inputs ---------- + +function runDetail(item) { + const top = head({ + title: item.name, + tagText: typeTag(item), + pills: statePill(item), + path: shownPath(fullPath(item)), + }); + if (item.state === 'cancelled') return top + body(note(t('run.cancelled_note'))); + const run = state.run; + if (item.state !== 'running' || !run) return top + body(''); + // The step belongs to the input being worked on; a package that waits for + // another input's library shows only what it has logged. + const cards = [ + progressCard(run.current === item ? run.step : null), + card(t('tab.log'), logBox(item.log ?? []), { wide: true }), + ]; + return top + body(grid(cards)); +} + +// ---------- results ---------- + +function recognitionCard(item) { + const profile = item.result?.info?.profile ?? null; + const observed = profile?.observed; + const known = profile && (profile.recognition !== 'not_attempted' || observed?.format); + const metadata = observed?.platform === 'il2cpp_metadata'; + // A run that stopped before it read the format still has the format the + // file's header showed when it was added. + const header = item.pre?.observed?.format ?? (item.kind === 'so' ? 'elf64_aarch64' : null); + const evidence = profile?.evidence ?? []; + const rows = [ + [t('ov.platform'), known ? esc(tv('platform', observed.platform)) : '—'], + !metadata && [t('ov.format'), mono(formatLabel(observed?.format ?? header))], + observed?.kind && [t('ov.kind'), esc(tv('kind', observed.kind))], + [ + t('ov.evidence'), + evidence.length + ? `${evidence.map((name) => pill('skip', tv('evidence', name))).join('')}` + : faint(t('ov.no_evidence')), + ], + ]; + // An input the page gave up on before the engine saw it was not looked at. + const aside = esc(tv('recognition', profile?.recognition ?? 'not_attempted')); + return card(t('ov.recognition'), kv(rows), { aside }); +} + +const OUTCOME_TONE = { succeeded: 'ok', not_attempted: 'skip' }; + +/** The routes a run tried. `shown` holds the messages already on the page. */ +function routesCard(item, shown) { + const info = item.result?.info; + const routes = info?.routes ?? []; + if (routes.length === 0) return card(t('ov.routes'), faint(t('ov.no_routes'))); + const rows = routes.map((route) => { + const selected = route.layout === info.profile?.selected; + const reasons = [ + ...(route.errors ?? []).map((message) => ({ tone: 'err', message })), + ...(route.warnings ?? []).map((message) => ({ tone: 'warn', message })), + ].filter(({ message }) => !shown.has(message.text)); + return ( + `
    ${esc(tv('layout', route.layout))}` + + `${selected ? `★ ${esc(t('ov.selected'))}` : ''}` + + `${pill(OUTCOME_TONE[route.outcome] ?? 'err', tv('outcome', route.outcome))}
    ` + + `${reasons.length ? messages(reasons, item.result.lang) : ''}
    ` + ); + }); + return card(t('ov.routes'), rows.join('')); +} + +const VALIDATION_TONE = { clean: 'ok', warnings: 'warn', failed: 'err' }; + +function validationCard(item, plan) { + const profile = item.result?.info?.profile; + if (!profile) return ''; + const status = profile.static_validation; + let why; + if (status === 'warnings' || status === 'failed') why = t(`ov.validation_${status}`); + else if (profile.observed?.platform === 'il2cpp_metadata' && status !== 'clean') why = t('ov.validation_metadata'); + else return ''; + const found = plan.validation.length ? messages(plan.validation, item.result.lang) : ''; + return card(t('ov.validation'), `${note(why)}${found}`, { + aside: pill(VALIDATION_TONE[status] ?? 'skip', tv('validation', status)), + }); +} + +/** One output: where it is kept, and the button that hands it over. */ +function outputValue(item, output, index) { + let kept = ''; + if (output.saved) { + kept = `${esc(t('web.saved', { path: shownPath(output.saved) }))}`; + } else if (output.refused) { + kept = `${esc(t('web.save_refused', { name: baseName(output.path) }))}`; + } else if (output.saveFailed) { + kept = `${esc(t('web.save_failed', { path: shownPath(output.saveFailed) }))}`; + } + return stack([ + `${mono(shownPath(output.path))}${output.embedded ? ` ${tag(t('web.embedded_metadata'))}` : ''}`, + `${esc(formatBytes(output.size))}` + + ``, + kept, + ]); +} + +function identityCard(item) { + const result = item.result; + // A library or a metadata blob is identified by what it was restored to. + // Anything else went through the Windows pipeline, which reads the whole + // input before it decides, so even a failure knows what it read. + const windows = ranAsModule(item); + const read = windows && result?.inputSha256; + if (result?.info?.status !== 'recovered' && !read) return ''; + const image = result.outputs.find((output) => !output.embedded); + let companion = null; + // Only a file named as a module has a `._` file to look for. + if (windows && candidateKind(item.relPath) === 'pe') { + const name = `${esc(`${baseName(item.relPath)}._`)}`; + if (result.companionUsed) { + const size = result.companionSize == null ? '' : ` · ${formatBytes(result.companionSize)}`; + companion = stack([esc(`${tv('companion', 'spliced')}${size}`), hash(result.companionSha256), name]); + } else if (item.companion && item.companion.state !== 'absent') { + companion = stack([esc(tv('companion', item.companion.state)), name]); + } else { + companion = esc(tv('companion', 'absent')); + } + } + const rows = [ + [t('ov.source'), stack([esc(formatBytes(item.size)), hash(result.inputSha256)])], + companion && [t('ov.companion'), companion], + image && [t('ov.recovered'), stack([esc(formatBytes(image.size)), hash(image.sha256)])], + ...result.outputs.map((output, index) => [t('ov.output'), outputValue(item, output, index)]), + ]; + return card(t('ov.identity'), kv(rows)); +} + +const yesNo = (value) => (value ? toned(t('common.yes'), 'ok') : faint(t('common.no'))); + +function metadataCard(metadata) { + const identity = metadata.identity; + const caps = identity?.capabilities; + const rows = [ + [t('ov.metadata_version'), esc(identity?.raw_version ?? metadata.version ?? '—')], + identity && [t('ov.metadata_layout'), esc(tv('metaLayout', identity.layout))], + caps && [t('ov.cap_seeded'), yesNo(caps.seeded_method_tokens)], + caps && [t('ov.cap_structural'), yesNo(caps.structural_method_tokens)], + caps && [t('ov.cap_indices'), yesNo(caps.method_index_restore)], + caps && [t('ov.cap_context'), yesNo(caps.method_index_requires_context)], + ]; + return card(t('ov.metadata'), kv(rows)); +} + +function elfCard(elf) { + const count = (value) => (value == null ? '—' : counted(value)); + return card( + t('ov.restored_elf'), + kv([ + [t('ov.format'), mono(formatLabel('elf64_aarch64'))], + [t('ov.elf_sections'), `${count(elf.sections)} · ${count(elf.segments)}`], + [t('ov.elf_symbols'), count(elf.dynamic_symbols)], + [t('ov.elf_relocs'), `${count(elf.dynamic_relocations)} · ${count(elf.pltgot_relocations)}`], + ]), + ); +} + +/** The path line of a finished input: where it is, how it ran, how long. */ +const lastRunLine = (item) => + `${shownPath(fullPath(item))} · ${t('DetailLastRun', { mode: modeLabel(), t: formatDuration(timeOf(item) ?? 0) })}`; + +function itemOverview(item) { + const info = item.result?.info; + const lang = item.result?.lang; + const plan = messagePlan(item); + const shown = new Set([...plan.top, ...plan.validation].map(({ message }) => message.text)); + const cards = []; + if (plan.top.length) { + cards.push(card(t('ov.messages'), messages(plan.top, lang, item.state === 'skipped'), { wide: true })); + } + cards.push(recognitionCard(item), routesCard(item, shown), stagesCard(item, shown)); + cards.push(validationCard(item, plan), identityCard(item)); + if (info?.metadata) cards.push(metadataCard(info.metadata)); + if (info?.elf) cards.push(elfCard(info.elf)); + return grid(cards); +} + +function itemDetail(item) { + const pills = [statePill(item)]; + if (item.result?.companionUsed) pills.push(pill('info', t('companion.spliced_pill'))); + const tabs = ['overview', 'log']; + const top = head({ + title: item.name, + tagText: typeTag(item), + pills: pills.join(''), + path: lastRunLine(item), + tabs, + exports: true, + }); + if (activeTab(tabs) === 'log') return top + body(logTab(item.log ?? []), false); + return top + body(itemOverview(item)); +} + +// ---------- packages ---------- + +/** Where an entry is: the archive that holds it, then its folder. */ +function entryPlace(item, entry) { + const source = entry.archive.label ? baseName(entry.archive.label) : item.name; + const folder = dirName(entry.target.path); + return `${source} › ${folder ? shownPath(`${folder}/`) : ''}`; +} + +const remappedOf = (entry) => entry.result?.info?.metadata?.remapped ?? null; + +function entryTable(item, entries) { + // A column no shown entry has a value for is left out. + const routes = entries.some((entry) => routeOf(entry) || remappedOf(entry) != null); + const outputs = entries.some((entry) => entry.result?.outputs?.length); + const columns = [['', 18], [t('col.name'), 240], [t('col.type'), 120], [t('col.status'), 110]]; + if (routes) columns.push([t('col.route'), 170]); + if (outputs) columns.push([t('ov.output'), 170]); + // The last column takes what the others leave. + columns.push([columns.pop()[0]]); + const rows = entries.map((entry) => { + const { tone, key } = outcomeOf(entry); + const remapped = remappedOf(entry); + let cells = + `${dot(tone)}` + + `
    ${esc(entry.name)}
    ${esc(entryPlace(item, entry))}
    ` + + `${tag(typeTag(entry))}${esc(t(key))}`; + if (routes) { + cells += + `
    ${esc(routeOf(entry) ?? '')}
    ` + + `${remapped == null ? '' : `
    ${esc(t('EntriesRemapped', { n: formatCount(remapped) }))}
    `}`; + } + if (outputs) cells += `${esc(shownPath(entry.result?.outputs?.[0]?.path ?? ''))}`; + return `${cells}`; + }); + return table(columns, rows, true); +} + +const ENTRY_TONE = { 'entryStatus.restored': 'ok', 'entryStatus.error': 'err' }; + +function packageOverview(item) { + const container = item.container; + const done = item.entries.filter(isDone); + const cards = []; + const blocks = container.problems.map((problem) => ({ + tone: 'warn', + message: { text: `${problem.path}: ${problem.message}` }, + })); + if (item.error) blocks.unshift({ tone: 'err', message: item.error }); + if (blocks.length) cards.push(card(t('ov.messages'), messages(blocks), { wide: true })); + + const nested = container.archives.slice(1).map((archive) => archive.label); + cards.push( + card( + t('pkg.title'), + kv([ + [t('pkg.kind'), esc(container.kind.toUpperCase())], + [t('pkg.entries'), counted(container.archives[0].entryCount)], + [t('pkg.candidates'), counted(item.entries.length)], + nested.length > 0 && [t('pkg.nested'), stack(nested.map((label) => mono(label)))], + ]) + note(t('pkg.note')), + ), + ); + const tally = new Map(); + for (const entry of done) { + const { key } = outcomeOf(entry); + tally.set(key, (tally.get(key) ?? 0) + 1); + } + const results = ['entryStatus.restored', 'entryStatus.unchanged', 'entryStatus.error', 'entryStatus.not_target'] + .filter((key) => tally.has(key)) + .map((key) => [t(key), ENTRY_TONE[key] ? toned(tally.get(key), ENTRY_TONE[key]) : String(tally.get(key))]); + cards.push(card(t('pkg.result'), kv(results))); + + // A bundle's manifests are those of the packages in it. + const manifests = container.archives.length > 1 ? container.archives.slice(1) : container.archives; + const rows = manifests.map( + (archive) => + `${esc(archive.label ? baseName(archive.label) : item.name)}` + + `${archive.identity ? mono(archive.identity[0]) : faint(t('pkg.unnamed'))}` + + `${esc(archive.identity?.[1] ?? '')}`, + ); + const columns = [[t('col.source'), 220], [t('pkg.package'), 260], [t('pkg.version')]]; + cards.push( + card(t('pkg.manifests'), table(columns, rows), { + wide: true, + aside: String(manifests.length), + }), + ); + const found = targetEntries(item); + cards.push( + found.length + ? card(t('pkg.targets'), entryTable(item, found), { wide: true }) + : card(null, note(t('pkg.no_targets')), { wide: true }), + ); + return grid(cards); +} + +function entriesTab(item) { + const done = item.entries.filter(isDone); + const others = done.filter(isNonTarget).length; + let shown = done.filter((entry) => state.showNonTargets || !isNonTarget(entry)); + if (shown.length === 0) shown = done; + const names = item.entries.map((entry) => `${entry.archive.label || item.relPath}::${entry.target.path}`); + return ( + `` + + entryTable(item, shown) + + fold( + 'inv', + `inv:${item.id}`, + esc(t('PkgInventory', { n: names.length })), + `
    ${esc(names.map(shownPath).join('\n'))}
    `, + ) + ); +} + +function packageDetail(item) { + const named = item.container.archives.find((archive) => archive.identity); + const pills = statePill(item) + (named ? pill('skip', named.identity[0]) : ''); + const tabs = ['overview', 'entries', 'log']; + const top = head({ + title: item.name, + tagText: typeTag(item), + pills, + path: lastRunLine(item), + tabs, + badge: { entries: item.entries.length }, + exports: true, + }); + const shown = activeTab(tabs); + if (shown === 'log') return top + body(logTab(item.log ?? []), false); + return top + body(shown === 'entries' ? entriesTab(item) : packageOverview(item)); +} + +function entryDetail(entry) { + const result = entry.result; + const info = result?.info; + const { tone, key } = outcomeOf(entry); + const plan = messagePlan(entry); + const blocks = [...plan.top, ...plan.validation]; + const image = result?.outputs.find((output) => !output.embedded); + const version = info?.metadata?.version ?? entry.metadataVersion; + const remapped = remappedOf(entry); + // What an entry is, is known once it was probed: one that is no target has + // only its name. + const kind = isNonTarget(entry) ? null : entry.kind === 'so' ? 'shared_library' : 'metadata'; + const rows = [ + [t('col.status'), toned(t(key), tone)], + kind && [t('col.type'), esc(tv('entryKind', kind))], + routeOf(entry) && [t('col.route'), esc(routeOf(entry))], + kind === 'metadata' && version != null && [t('ov.metadata_version'), esc(version)], + remapped != null && [t('entries.remapped_label'), counted(remapped)], + result?.inputSha256 && [t('ov.source'), hash(result.inputSha256)], + image && [t('ov.recovered'), stack([esc(formatBytes(image.size)), hash(image.sha256)])], + ...(result?.outputs ?? []).map((output, index) => [t('ov.output'), outputValue(entry, output, index)]), + ]; + // The label column is as wide for one entry as for any other. + const labels = ['col.status', 'col.type', 'col.route', 'ov.metadata_version', 'entries.remapped_label', 'ov.source', 'ov.recovered', 'ov.output']; + const cards = []; + if (blocks.length) { + cards.push(card(t('ov.messages'), messages(blocks, result?.lang, entry.state === 'skipped'), { wide: true })); + } + cards.push(card(t('entries.title'), kv(rows, labels.map((label) => t(label))))); + if (info?.elf) cards.push(elfCard(info.elf)); + const top = head({ + title: entry.name, + tagText: typeTag(entry), + pills: pill(tone, t(key)), + path: shownPath(fullPath(entry)), + tabs: ['overview'], + }); + return top + body(grid(cards)); +} + +// ---------- dispatch ---------- + +function empty() { + const kinds = ['.exe', '.dll', '.exe._ / .dll._', 'global-metadata.dat', '.so', '.apk', '.apks', '.xapk', t('empty.folders')]; + return ( + `
    ` + + `

    ${esc(t('empty.title'))}

    ` + + `
    ${kinds.map((kind) => `${esc(kind)}`).join('')}
    ` + + `
    ` + + `
    ` + + `

    ${esc(t('empty.local'))}

    ` + ); +} + +const pick = () => `
    ${esc(t('detail.pick'))}
    `; + +/** The detail pane for the selection. */ +export function detail() { + if (state.groups.length === 0) return empty(); + const current = state.selected && find(state.selected); + if (!current) return pick(); + if (current.group) return groupDetail(current.group); + let item = current.item; + if (item.isEntry) { + if (isDone(item) && !isBusy(item.parent)) return entryDetail(item); + // An entry that is running again is shown as its package. + item = item.parent; + } + if (isBusy(item) || item.state === 'cancelled') return runDetail(item); + if (!isDone(item)) return pendingDetail(item); + // A package that could not be listed is shown as the input that failed. + return item.kind === 'package' && item.container ? packageDetail(item) : itemDetail(item); +} diff --git a/web/engine.js b/web/engine.js new file mode 100644 index 0000000..d7a22ab --- /dev/null +++ b/web/engine.js @@ -0,0 +1,196 @@ +// The page's side of `worker.js`: one compiled module, and workers that live +// for one job (a recovery) or for one scan (the probes). + +let compiled = null; + +/** + * Fetch and compile the engine once. Workers instantiate this module, so none + * of them downloads or compiles it again. + */ +export function loadEngine() { + compiled ??= (async () => { + const url = new URL('./pkg/senbei_wasm_bg.wasm', import.meta.url); + try { + return await WebAssembly.compileStreaming(fetch(url)); + } catch { + // A server that sends the wrong content type cannot be streamed. + const response = await fetch(url); + if (!response.ok) throw new Error(`engine download failed (${response.status})`); + return WebAssembly.compile(await response.arrayBuffer()); + } + })(); + compiled.catch(() => { + compiled = null; + }); + return compiled; +} + +/** The engine ended without an answer: a trap, or the worker itself failed. */ +export class EngineStopped extends Error { + constructor(message, trap) { + super(message); + this.name = 'EngineStopped'; + this.trap = trap; + } +} + +/** One worker and the requests it has not answered yet. */ +class Session { + #worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' }); + #pending = new Map(); + #next = 1; + #sentEngine = false; + closed = false; + + constructor() { + this.#worker.onmessage = (event) => { + const message = event.data; + const pending = this.#pending.get(message.id); + if (!pending) return; + if (message.type === 'done') { + this.#pending.delete(message.id); + pending.resolve(message); + } else if (message.type === 'error') { + this.#pending.delete(message.id); + pending.reject( + message.trap ? new EngineStopped(message.message, true) : new Error(message.message), + ); + } else { + pending.on?.(message); + } + }; + this.#worker.onerror = (event) => { + event.preventDefault?.(); + this.#fail(new EngineStopped(event.message || 'worker failed', false)); + }; + this.#worker.onmessageerror = () => { + this.#fail(new EngineStopped('worker reply could not be read', false)); + }; + } + + #fail(error) { + for (const pending of this.#pending.values()) pending.reject(error); + this.#pending.clear(); + this.close(); + } + + /** Send one request. `on` receives the replies that precede the last one. */ + async request(message, on) { + const wasm = await loadEngine(); + if (this.closed) throw new EngineStopped('worker was closed', false); + const id = this.#next; + this.#next += 1; + // The worker instantiates the module from its first request. + const first = !this.#sentEngine; + this.#sentEngine = true; + return new Promise((resolve, reject) => { + this.#pending.set(id, { resolve, reject, on }); + this.#worker.postMessage(first ? { ...message, id, wasm } : { ...message, id }); + }); + } + + close() { + if (this.closed) return; + this.closed = true; + this.#worker.terminate(); + this.#fail(new EngineStopped('worker was closed', false)); + } +} + +/** + * Run one recovery in a worker of its own. + * + * `request` is `{ op: 'pe' | 'so' | 'metadata', input, lang, ... }`. `on.step` + * is called as each step starts and `on.result` once the outcome is known, + * before its digests are. Resolves to `{ op, info, image, embedded, + * moduleBytes, identity }`, `op` being the job that ran. Rejects with + * [`EngineStopped`] when the engine ended without an answer. `signal` ends the + * worker and rejects. + */ +export async function runJob(request, on = {}, signal) { + const session = new Session(); + const abort = () => session.close(); + signal?.addEventListener('abort', abort, { once: true }); + const outcome = { op: request.op, info: null, image: null, embedded: null, moduleBytes: null, identity: null }; + try { + if (signal?.aborted) throw new EngineStopped('cancelled', false); + await session.request(request, (message) => { + if (message.type === 'step') { + on.step?.(message); + } else if (message.type === 'result') { + outcome.info = message.info; + outcome.image = message.image; + outcome.embedded = message.embedded; + outcome.moduleBytes = message.module; + on.result?.(outcome); + } else if (message.type === 'identity') { + outcome.identity = { + input: message.input, + image: message.image, + embedded: message.embedded, + companion: message.companion ?? null, + }; + } + }); + return outcome; + } finally { + signal?.removeEventListener('abort', abort); + session.close(); + } +} + +/** A probe above this size leaves its worker holding that much memory. */ +const RESTART_AFTER_BYTES = 32 * 1024 * 1024; + +/** + * The scan's probes. One worker answers them in turn; it is replaced after a + * trap and after a large library probe, whose memory it would otherwise keep. + */ +export class Prober { + #session = null; + + #open() { + if (!this.#session || this.#session.closed) this.#session = new Session(); + return this.#session; + } + + async #ask(message) { + try { + return await this.#open().request(message); + } catch (error) { + this.close(); + throw error; + } + } + + /** What a file's first bytes are: `{ kind, profile }`. */ + prefix(bytes) { + return this.#ask({ op: 'prefix', bytes }); + } + + /** Probe a whole AArch64 library; resolves to its probe profile. */ + async library(input, size) { + const reply = await this.#ask({ op: 'probe-so', input }); + if (size > RESTART_AFTER_BYTES) this.close(); + return reply.profile; + } + + /** `[package, version]` from a manifest, or `null`. */ + async manifest(bytes, truncated) { + return (await this.#ask({ op: 'manifest', bytes, truncated })).identity; + } + + /** + * The engine's message for a package refused over an entry name that leaves + * it: `{ text, local, lang }`, with `local` worded in `lang`. + */ + async unsafeEntry(packagePath, lang) { + const reply = await this.#ask({ op: 'unsafe-entry', package: packagePath, lang }); + return { ...reply.message, lang }; + } + + close() { + this.#session?.close(); + this.#session = null; + } +} diff --git a/web/i18n.js b/web/i18n.js new file mode 100644 index 0000000..053c6f9 --- /dev/null +++ b/web/i18n.js @@ -0,0 +1,60 @@ +// The page's text: one language catalog, loaded on demand. +// +// The catalogs in `i18n/` are generated from the desktop GUI's approved +// wording (see `tools/gen-i18n.mjs`). Only the active language is fetched. + +export const LANGUAGES = [ + ['en', 'English'], + ['zh-CN', '简体中文'], + ['zh-TW', '繁體中文'], + ['ja', '日本語'], + ['ko', '한국어'], +]; + +let catalog = {}; +let active = 'en'; + +/** The active language tag. */ +export const language = () => active; + +/** Fetch and switch to `tag`. An unknown tag falls back to English. */ +export async function loadLanguage(tag) { + const known = LANGUAGES.some(([code]) => code === tag) ? tag : 'en'; + catalog = (await import(`./i18n/${known}.js`)).default; + active = known; + document.documentElement.lang = known; +} + +/** The text for `key`, with `{name}` placeholders filled from `vars`. */ +export function t(key, vars) { + const text = catalog[key] ?? key; + if (!vars) return text; + return text.replace(/\{(\w+)\}/g, (match, name) => (name in vars ? String(vars[name]) : match)); +} + +/** The label of a report value such as `layout.exe_style`. */ +export function tv(prefix, value) { + if (value === null || value === undefined) return '—'; + return catalog[`${prefix}.${value}`] ?? String(value).replace(/_/g, ' '); +} + +/** + * A message in the page language. + * + * A message the page raised carries its catalog `key`. An engine message + * carries its English `text` and, in `local`, its wording in the language it + * was made in: `lang`, or the message's own `lang` when it has one. After a + * language switch only the English is right. + */ +export function show(message, lang = active) { + if (message?.key) return t(message.key, message.vars); + if ((message?.lang ?? lang) !== active) return message?.text ?? ''; + return message?.local ?? message?.text ?? ''; +} + +/** The part of a message its page-language wording leaves out, if any. */ +export function technical(message, lang = active) { + if (message?.tech) return message.tech; + if (message?.key || (message?.lang ?? lang) !== active) return null; + return message?.local && message.local !== message.text ? message.text : null; +} diff --git a/web/i18n/en.js b/web/i18n/en.js new file mode 100644 index 0000000..0d39756 --- /dev/null +++ b/web/i18n/en.js @@ -0,0 +1,268 @@ +// Generated by web/tools/gen-i18n.mjs from senbei-gui/src/text and +// web/i18n/web-strings.json. Edit the wording there and run the generator. +export default { + "tb.add_files": "Add files…", + "tb.add_folder": "Add folder…", + "tb.unpack": "Unpack", + "tb.unpack.all": "Unpack all", + "tb.output": "Output:", + "tb.settings": "Settings", + "empty.title": "Drop protected files here", + "empty.folders": "folders", + "empty.local": "Everything runs on this computer. Inputs are never executed or uploaded.", + "drag.title": "Release to add", + "inputs.title": "Inputs", + "inputs.clear": "Clear", + "inputs.search": "Filter by name", + "inputs.none": "No inputs match the filter.", + "filter.all": "All", + "filter.ok": "Recovered", + "filter.suspect": "Suspect", + "filter.failed": "Failed", + "filter.skipped": "Skipped", + "group.files": "Added files", + "mode.unpack": "Unpacked", + "menu.copy_path": "Copy path", + "menu.remove": "Remove from list", + "pending.not_run": "Not run yet", + "pending.not_protected": "Not protected", + "pending.identified": "Identified", + "pending.next": "Actions", + "pending.not_protected_note": "No supported protection was detected in this file.", + "scan.running": "Scanning", + "scan.found": "Candidates so far", + "run.running": "Running…", + "run.queued": "Queued", + "run.will_not_run": "Will not run", + "run.stopping": "Stopping after the current input…", + "run.cancel": "Cancel", + "run.progress": "Progress", + "run.cancelled_note": "The job was cancelled before reaching this input.", + "step.decrypt_header": "Decrypting file header", + "step.decrypt_payload": "Decrypting payload", + "step.locate_config": "Locating config layout", + "step.decrypt_stage2": "Decrypting stage 2", + "step.decrypt_stages_3_5": "Decrypting stages 3–5", + "step.decrypt_sections": "Decrypting section data", + "step.load_sections": "Loading and decompressing sections", + "step.decrypt_imports": "Decrypting import strings", + "step.rebuild_headers": "Reconstructing PE headers", + "step.init_keys": "Initializing keys", + "step.decrypt_key_table": "Decrypting key table", + "step.decrypt_primary": "Decrypting primary descriptor", + "step.relocs_params": "Processing relocations and decompression parameters", + "step.decrypt_block1": "Decrypting code block 1", + "step.decrypt_block23": "Decrypting code blocks 2–3", + "step.decrypt_block4": "Decrypting code block 4", + "step.dll_sections": "Decrypting and decompressing sections", + "step.fix_headers": "Fixing up PE header and section table", + "step.pe32_stages": "Decrypting stages", + "step.pe32_eighth": "Decrypting the eighth stage", + "step.pe32_load": "Loading and decompressing file data", + "step.pe32_text": "Decrypting .text", + "step.pe32_text_skip": "Skipping .text (already plaintext)", + "step.pe32_rebuild": "Rebuilding PE file layout", + "step.android_primary": "Decoding the primary container", + "step.android_aux": "Decoding the auxiliary ELF container", + "step.android_tables": "Rebuilding dynamic-linker tables", + "detail.pick": "Select an input or a group on the left.", + "detail.export_json": "Export JSON", + "detail.export_text": "Export text", + "detail.copy": "Copy", + "detail.technical": "Technical detail", + "companion.spliced_pill": "Companion paired", + "tab.overview": "Overview", + "tab.log": "Log", + "tab.entries": "Entries", + "batch.summary": "Summary", + "batch.inputs": "Inputs", + "batch.scan": "Folder scan", + "batch.non_target": "Non-targets skipped", + "batch.walk_errors": "Unreadable entries", + "batch.probe_errors": "Probe errors", + "batch.scan_note": "Folder scans check .exe, .dll, .so, global-metadata.dat, and Android app packages.", + "batch.scan_incomplete": "Analysis is incomplete: some folder entries or selected files could not be examined.", + "pkg.title": "Package", + "pkg.kind": "Package type", + "pkg.package": "Package name", + "pkg.version": "Version", + "pkg.entries": "Top-level entries", + "pkg.candidates": "Entries to probe", + "pkg.nested": "Nested packages", + "pkg.note": "Only .so and global-metadata.dat entries are extracted and probed.", + "pkg.result": "Result", + "pkg.manifests": "Manifests", + "pkg.unnamed": "not named", + "pkg.targets": "Protected entries and metadata", + "pkg.no_targets": "No protected entries were detected in this package.", + "entries.title": "Entry", + "entries.remapped_label": "Method fields remapped", + "col.name": "Name", + "col.type": "Type", + "col.outcome": "Outcome", + "col.route": "Route", + "col.time": "Time", + "col.source": "Source", + "col.status": "Status", + "common.yes": "yes", + "common.no": "no", + "ov.messages": "Messages", + "ov.recognition": "Recognition", + "ov.platform": "Platform", + "ov.format": "Format", + "ov.kind": "Kind", + "ov.metadata": "il2cpp metadata", + "ov.metadata_version": "Metadata version", + "ov.metadata_layout": "Layout definition", + "ov.cap_seeded": "Seeded method tokens", + "ov.cap_structural": "Structural method tokens", + "ov.cap_indices": "Method-index restoration", + "ov.cap_context": "Needs application context", + "ov.evidence": "Evidence", + "ov.no_evidence": "No protection evidence", + "ov.routes": "Recovery routes", + "ov.selected": "selected", + "ov.no_routes": "No route was attempted.", + "ov.stages": "Stages", + "ov.validation": "Static validation", + "ov.validation_metadata": "This validation checks PE and ELF structure. Metadata tables are validated during transformation.", + "ov.validation_warnings": "The restored image has structural warnings and may not run. It is marked as suspect, and unpack still writes the output file.", + "ov.validation_failed": "Static validation found a fatal structural error in the restored image, which is unlikely to run. It is marked as suspect, and unpack still writes the output file.", + "ov.identity": "Identity", + "ov.source": "Input", + "ov.companion": "Companion", + "ov.recovered": "Restored image", + "ov.output": "Output", + "ov.restored_elf": "Restored ELF", + "ov.elf_sections": "Sections · segments", + "ov.elf_symbols": "Dynamic symbols", + "ov.elf_relocs": "Relocations · PLT", + "log.f_all": "All", + "log.f_nosteps": "Hide steps", + "log.f_problems": "Problems only", + "log.copy": "Copy log", + "log.lv_info": "INFO", + "log.lv_step": "STEP", + "log.lv_warn": "WARN", + "log.lv_error": "ERROR", + "status.ready": "Ready", + "legal.title": "Legal notice: read before use", + "legal.p1": "Senbei is a research and interoperability tool for lawful reverse engineering, security research, and preservation of software you already legitimately possess. Only process binaries you own or are explicitly authorized to analyze.", + "legal.p2": "Circumventing technological protection measures may be restricted in your jurisdiction (for example under DMCA §1201 in the United States, which contains exemptions for security research and interoperability). Ensuring your use is lawful is your responsibility.", + "legal.p3": "Senbei performs a purely static transformation of files on your computer: it bypasses no access control by itself, derives what it needs from the input file, ships no vendor code, and never executes or uploads its inputs. One Android packaging variant’s embedded metadata layer is unwrapped with an XOR keystream recovered during analysis of a single build; that keystream is research output shipped with the tool, not a vendor-distributed key.", + "legal.p4": "Senbei does not enable online play, license fraud, or cheating. Do not redistribute decrypted outputs or upload them anywhere. This software is provided “as is”, without warranty of any kind; the authors accept no liability for misuse. “CrackProof” is a trademark of its owner; this project is not affiliated with or endorsed by the vendor or any publisher.", + "legal.accept": "I understand and accept", + "settings.title": "Settings", + "settings.tab_general": "General", + "settings.tab_memory": "Memory", + "settings.tab_about": "About", + "settings.language": "Language", + "settings.output": "Default output folder", + "settings.output_recent": "Last used folder", + "settings.output_choose": "Choose a folder…", + "settings.reset": "Reset to defaults", + "settings.done": "Done", + "about.desc": "Static unpacker for CrackProof-protected Windows PE files and Android AArch64 shared libraries.", + "about.license": "License", + "about.source": "Source code", + "about.legal": "Show legal notice", + "status.ok": "Recovered", + "status.suspect": "Suspect", + "status.skipped": "Skipped", + "status.error": "Error", + "status.incomplete": "Analysis incomplete", + "entryStatus.restored": "Restored", + "entryStatus.not_target": "Not a target", + "entryStatus.unchanged": "Unchanged", + "entryStatus.error": "Error", + "entryKind.shared_library": "Shared library", + "entryKind.metadata": "il2cpp metadata", + "recognition.not_attempted": "Not attempted", + "recognition.recognized": "Recognized", + "recognition.not_recognized": "Not recognized", + "recognition.blocked": "Blocked", + "outcome.succeeded": "Succeeded", + "outcome.rejected": "Rejected", + "outcome.failed": "Failed", + "outcome.not_attempted": "Not attempted", + "validation.clean": "Clean", + "validation.warnings": "Warnings", + "validation.failed": "Failed", + "validation.not_run": "Not run", + "stage.detection": "Detection", + "stage.recovery": "Recovery", + "stage.static_validation": "Static validation", + "stage.output_write": "Output write", + "stageStatus.ok": "OK", + "stageStatus.skipped": "Skipped", + "stageStatus.failed": "Failed", + "stageStatus.blocked": "Blocked", + "evidence.header_magic": "Header magic", + "evidence.companion_spliced": "Companion spliced", + "evidence.external_companion_declaration": "Declares an external companion", + "evidence.private_section": "Private section", + "evidence.aes_schedule": "AES key schedule", + "evidence.validated_metadata_transform": "Validated metadata transform", + "platform.windows_pe": "Windows PE", + "platform.android_elf": "Android ELF", + "platform.il2cpp_metadata": "il2cpp metadata", + "kind.native_exe": "Native executable", + "kind.managed_exe": ".NET executable", + "kind.native_dll": "Native DLL", + "kind.managed_dll": ".NET assembly (DLL)", + "kindShort.native_exe": "EXE", + "kindShort.managed_exe": ".NET EXE", + "kindShort.native_dll": "DLL", + "kindShort.managed_dll": ".NET DLL", + "layout.exe_style": "EXE-style loader", + "layout.dll": "DLL loader", + "layout.android_staged": "Android staged loader", + "layout.metadata_seeded": "Seeded metadata transform", + "layout.metadata_structural": "Structural metadata transform", + "layout.metadata_method_indices": "Metadata method-index recovery", + "metaLayout.known": "Known", + "metaLayout.context_required": "Needs application context", + "metaLayout.unverified": "Not verified", + "companion.absent": "None", + "companion.spliced": "Spliced", + "companion.paired": "Paired", + "companion.unmatched": "Does not match", + "companion.unreadable": "Unreadable", + "TbUnpackN": "Unpack ({n})", + "GroupScanning": "Scanning… candidates so far: {n}", + "ScanStatus": "Scanning {p}… candidates so far: {n}", + "RunStep": "Step {i}/{n} · {s}", + "DetailLastRun": "{mode} · {t}", + "PkgInventory": "Candidate entries: {n}", + "EntriesOthers": "Other entries (not targets): {n}", + "EntriesSummary": "Targets: {n}", + "EntriesShowNonTargets": "Show non-targets ({n})", + "EntriesRemapped": "Method fields remapped: {n}", + "LogRunStarted": "{mode} started · inputs: {n}", + "LogScan": "Scan finished: candidates {n}, non-targets skipped {s}", + "LogInputStarted": "Input {i}/{n}: {p}", + "LogCompanion": "Companion paired: {p}", + "LogStep": "Step {i}/{n}: {s}", + "LogEntry": "Entry {p}: {o}", + "LogInputFinished": "Finished: {o} ({t})", + "LogSummary": "{ok} recovered · {suspect} suspect · {failed} failed · {skipped} skipped", + "AboutVersion": "Version {v}", + "TagMetadata": "il2cpp metadata v{v}", + "web.unpack_tip": "Recover the selected inputs. Results are kept in this tab for download.", + "web.unpack_desc": "Recover it. The result is kept in this tab for download.", + "web.download": "Download", + "web.download_all": "Download all (.zip)", + "web.out_downloads": "Browser download", + "web.out_tip": "Where unpacked files are saved.", + "web.out_folder_help": "When you choose a folder, Senbei saves to unpack/ inside it. Files the browser won’t save directly (such as .dll files) go into senbei-remaining.*.zip. Extract it into unpack/.", + "web.out_unsupported": "This browser cannot write to a folder, so recovered files are saved as downloads.", + "web.limit": "Input size limit", + "web.limit_help": "Larger inputs are not read. Recovery keeps the input and the restored image in memory at the same time.", + "web.over_limit": "This input is {size}, over the {limit} input size limit. Raise the limit in Settings, then run it again.", + "web.engine_stopped": "The recovery engine stopped before finishing. This input may need more memory than the browser can provide.", + "web.embedded_metadata": "Embedded metadata", + "web.saved": "Saved to {path}", + "web.save_failed": "Could not save {path}.", + "web.save_refused": "This browser does not allow saving {name} to a folder. It is kept in this tab for download.", + "web.read_failed": "Could not read this input.", +}; diff --git a/web/i18n/ja.js b/web/i18n/ja.js new file mode 100644 index 0000000..e17e18c --- /dev/null +++ b/web/i18n/ja.js @@ -0,0 +1,268 @@ +// Generated by web/tools/gen-i18n.mjs from senbei-gui/src/text and +// web/i18n/web-strings.json. Edit the wording there and run the generator. +export default { + "tb.add_files": "ファイルを追加…", + "tb.add_folder": "フォルダーを追加…", + "tb.unpack": "アンパック", + "tb.unpack.all": "すべてアンパック", + "tb.output": "出力:", + "tb.settings": "設定", + "empty.title": "保護されたファイルをここにドロップ", + "empty.folders": "フォルダー", + "empty.local": "処理はすべてこのコンピューター上で完結します。入力が実行されたりアップロードされたりすることはありません。", + "drag.title": "ドロップして追加", + "inputs.title": "入力", + "inputs.clear": "クリア", + "inputs.search": "名前で絞り込み", + "inputs.none": "条件に一致する入力はありません。", + "filter.all": "すべて", + "filter.ok": "復元済み", + "filter.suspect": "要注意", + "filter.failed": "失敗", + "filter.skipped": "スキップ", + "group.files": "追加したファイル", + "mode.unpack": "アンパック済み", + "menu.copy_path": "パスをコピー", + "menu.remove": "リストから削除", + "pending.not_run": "未実行", + "pending.not_protected": "保護なし", + "pending.identified": "識別結果", + "pending.next": "実行する操作", + "pending.not_protected_note": "このファイルには対応する保護が見つからなかったため、復元する対象がありません。", + "scan.running": "スキャン中", + "scan.found": "これまでの候補", + "run.running": "実行中…", + "run.queued": "待機中", + "run.will_not_run": "実行されません", + "run.stopping": "現在の入力の完了後に停止します…", + "run.cancel": "キャンセル", + "run.progress": "進行状況", + "run.cancelled_note": "この入力に到達する前にジョブがキャンセルされました。", + "step.decrypt_header": "ファイルヘッダーを復号中", + "step.decrypt_payload": "ペイロードを復号中", + "step.locate_config": "構成レイアウトを特定中", + "step.decrypt_stage2": "ステージ2を復号中", + "step.decrypt_stages_3_5": "ステージ3–5を復号中", + "step.decrypt_sections": "セクションデータを復号中", + "step.load_sections": "セクションを読み込み・展開中", + "step.decrypt_imports": "インポート文字列を復号中", + "step.rebuild_headers": "PEヘッダーを再構築中", + "step.init_keys": "鍵を初期化中", + "step.decrypt_key_table": "鍵テーブルを復号中", + "step.decrypt_primary": "プライマリ記述子を復号中", + "step.relocs_params": "再配置と展開パラメーターを処理中", + "step.decrypt_block1": "コードブロック1を復号中", + "step.decrypt_block23": "コードブロック2–3を復号中", + "step.decrypt_block4": "コードブロック4を復号中", + "step.dll_sections": "セクションを復号・展開中", + "step.fix_headers": "PEヘッダーとセクションテーブルを修正中", + "step.pe32_stages": "ステージを復号中", + "step.pe32_eighth": "第8ステージを復号中", + "step.pe32_load": "ファイルデータを読み込み・展開中", + "step.pe32_text": ".textを復号中", + "step.pe32_text_skip": ".textをスキップ中 (すでに平文)", + "step.pe32_rebuild": "PEファイルレイアウトを再構築中", + "step.android_primary": "プライマリコンテナーをデコード中", + "step.android_aux": "ELF再構築用コンテナーをデコード中", + "step.android_tables": "動的リンカーテーブルを再構築中", + "detail.pick": "左側から入力またはグループを選択してください。", + "detail.export_json": "JSONをエクスポート", + "detail.export_text": "テキストをエクスポート", + "detail.copy": "コピー", + "detail.technical": "技術詳細", + "companion.spliced_pill": "コンパニオン対応付け済み", + "tab.overview": "概要", + "tab.log": "ログ", + "tab.entries": "エントリ", + "batch.summary": "集計", + "batch.inputs": "入力", + "batch.scan": "フォルダースキャン", + "batch.non_target": "対象外 (スキップ)", + "batch.walk_errors": "読み取れないフォルダー項目", + "batch.probe_errors": "プローブエラー", + "batch.scan_note": "フォルダーのスキャンでは、.exe、.dll、.so、global-metadata.datとAndroidアプリパッケージを検査します。", + "batch.scan_incomplete": "解析が不完全です。一部のフォルダー項目または選択したファイルを調査できませんでした。", + "pkg.title": "パッケージ", + "pkg.kind": "パッケージ種別", + "pkg.package": "パッケージ名", + "pkg.version": "バージョン", + "pkg.entries": "トップレベルエントリ", + "pkg.candidates": "プローブ対象エントリ", + "pkg.nested": "ネストされたパッケージ", + "pkg.note": ".soとglobal-metadata.datのエントリのみを抽出して検査します。", + "pkg.result": "結果", + "pkg.manifests": "マニフェスト", + "pkg.unnamed": "名前なし", + "pkg.targets": "保護されたエントリとメタデータ", + "pkg.no_targets": "このパッケージに保護されたエントリはないため、復元する対象がありません。", + "entries.title": "エントリ", + "entries.remapped_label": "再マップされたメソッドフィールド", + "col.name": "名前", + "col.type": "種別", + "col.outcome": "結果", + "col.route": "ルート", + "col.time": "時間", + "col.source": "ソース", + "col.status": "状態", + "common.yes": "あり", + "common.no": "なし", + "ov.messages": "メッセージ", + "ov.recognition": "認識", + "ov.platform": "プラットフォーム", + "ov.format": "フォーマット", + "ov.kind": "種類", + "ov.metadata": "il2cppメタデータ", + "ov.metadata_version": "メタデータバージョン", + "ov.metadata_layout": "レイアウト定義", + "ov.cap_seeded": "シード方式のメソッドトークン", + "ov.cap_structural": "構造方式のメソッドトークン", + "ov.cap_indices": "メソッドインデックス復元", + "ov.cap_context": "アプリケーションコンテキストが必要", + "ov.evidence": "根拠", + "ov.no_evidence": "保護の根拠なし", + "ov.routes": "復元ルート", + "ov.selected": "選択済み", + "ov.no_routes": "試行されたルートはありません。", + "ov.stages": "ステージ", + "ov.validation": "静的検証", + "ov.validation_metadata": "ここでの静的検証はPEとELFの構造を対象とします。メタデータのテーブルは変換処理中に検証します。", + "ov.validation_warnings": "復元イメージに構造上の問題が検出されたため、正常に動作しない可能性があります。「要注意」として集計されますが、アンパック時にはそのまま書き込まれます。", + "ov.validation_failed": "静的検証で復元イメージに致命的な構造上の問題が見つかったため、動作しない可能性が高いです。「要注意」として扱われますが、アンパック時にはファイルが保存されます。", + "ov.identity": "識別情報", + "ov.source": "入力", + "ov.companion": "コンパニオン", + "ov.recovered": "復元イメージ", + "ov.output": "出力", + "ov.restored_elf": "復元ELF", + "ov.elf_sections": "セクション · セグメント", + "ov.elf_symbols": "動的シンボル", + "ov.elf_relocs": "再配置 · PLT", + "log.f_all": "すべて", + "log.f_nosteps": "ステップを隠す", + "log.f_problems": "問題のみ", + "log.copy": "ログをコピー", + "log.lv_info": "INFO", + "log.lv_step": "STEP", + "log.lv_warn": "WARN", + "log.lv_error": "ERROR", + "status.ready": "準備完了", + "legal.title": "法的通知: ご利用前にお読みください", + "legal.p1": "Senbeiは、すでに正当に所有しているソフトウェアの合法的なリバースエンジニアリング、セキュリティ研究、および保全のための研究・相互運用性ツールです。ご自身が所有するバイナリ、または解析の明示的な許可を得ているバイナリのみを処理してください。", + "legal.p2": "技術的保護手段の回避は、お住まいの法域で制限されている場合があります (たとえば米国のDMCA §1201。同条にはセキュリティ研究および相互運用性のための例外規定があります)。ご利用が合法であることを確認するのはご自身の責任です。", + "legal.p3": "Senbeiはお使いのコンピューター上のファイルに対して純粋に静的な変換を行います。それ自体でアクセス制御を回避することはなく、必要な情報は入力ファイルから導出し、ベンダーのコードを同梱せず、入力を実行したりアップロードしたりすることも一切ありません。あるAndroidパッケージング形式における埋め込みメタデータ層は、単一ビルドの解析中に復元されたXORキーストリームで解除されます。このキーストリームは本ツールに同梱された研究成果物であり、ベンダーが配布した鍵ではありません。", + "legal.p4": "Senbeiはオンラインプレイ、ライセンス詐欺、またはチート行為を可能にするものではありません。復号された出力を再配布したり、どこかにアップロードしたりしないでください。本ソフトウェアは「現状有姿」で提供され、いかなる種類の保証もありません。誤用について作成者は一切の責任を負いません。「CrackProof」はその所有者の商標です。本プロジェクトはベンダーやいかなるパブリッシャーとも提携しておらず、承認も受けていません。", + "legal.accept": "理解して同意する", + "settings.title": "設定", + "settings.tab_general": "一般", + "settings.tab_memory": "メモリ", + "settings.tab_about": "バージョン情報", + "settings.language": "言語", + "settings.output": "既定の出力フォルダー", + "settings.output_recent": "前回使用したフォルダー", + "settings.output_choose": "フォルダーを選択…", + "settings.reset": "既定値に戻す", + "settings.done": "完了", + "about.desc": "CrackProofで保護されたWindows PEファイルおよびAndroid AArch64共有ライブラリ用の静的アンパッカー。", + "about.license": "ライセンス", + "about.source": "ソースコード", + "about.legal": "法的通知を表示", + "status.ok": "復元済み", + "status.suspect": "要注意", + "status.skipped": "スキップ", + "status.error": "エラー", + "status.incomplete": "解析不完全", + "entryStatus.restored": "復元済み", + "entryStatus.not_target": "対象外", + "entryStatus.unchanged": "変更なし", + "entryStatus.error": "エラー", + "entryKind.shared_library": "共有ライブラリ", + "entryKind.metadata": "il2cppメタデータ", + "recognition.not_attempted": "未試行", + "recognition.recognized": "認識済み", + "recognition.not_recognized": "未認識", + "recognition.blocked": "ブロック", + "outcome.succeeded": "成功", + "outcome.rejected": "却下", + "outcome.failed": "失敗", + "outcome.not_attempted": "未試行", + "validation.clean": "問題なし", + "validation.warnings": "警告あり", + "validation.failed": "失敗", + "validation.not_run": "未実行", + "stage.detection": "検出", + "stage.recovery": "復元", + "stage.static_validation": "静的検証", + "stage.output_write": "出力書き込み", + "stageStatus.ok": "OK", + "stageStatus.skipped": "スキップ", + "stageStatus.failed": "失敗", + "stageStatus.blocked": "ブロック", + "evidence.header_magic": "ヘッダーマジック", + "evidence.companion_spliced": "コンパニオン連結", + "evidence.external_companion_declaration": "外部コンパニオン宣言", + "evidence.private_section": "専用セクション", + "evidence.aes_schedule": "AES鍵スケジュール", + "evidence.validated_metadata_transform": "検証済みメタデータ変換", + "platform.windows_pe": "Windows PE", + "platform.android_elf": "Android ELF", + "platform.il2cpp_metadata": "il2cppメタデータ", + "kind.native_exe": "ネイティブ実行ファイル", + "kind.managed_exe": ".NET実行ファイル", + "kind.native_dll": "ネイティブDLL", + "kind.managed_dll": ".NETアセンブリ (DLL)", + "kindShort.native_exe": "EXE", + "kindShort.managed_exe": ".NET EXE", + "kindShort.native_dll": "DLL", + "kindShort.managed_dll": ".NET DLL", + "layout.exe_style": "EXE形式ローダー", + "layout.dll": "DLLローダー", + "layout.android_staged": "Android段階型ローダー", + "layout.metadata_seeded": "シード方式メタデータ変換", + "layout.metadata_structural": "構造方式メタデータ変換", + "layout.metadata_method_indices": "メタデータメソッドインデックス復元", + "metaLayout.known": "既知", + "metaLayout.context_required": "アプリケーションコンテキストが必要", + "metaLayout.unverified": "未検証", + "companion.absent": "なし", + "companion.spliced": "連結済み", + "companion.paired": "対応付け済み", + "companion.unmatched": "不一致", + "companion.unreadable": "読み取り不能", + "TbUnpackN": "アンパック ({n})", + "GroupScanning": "スキャン中… これまでの候補: {n}", + "ScanStatus": "{p}をスキャン中… これまでの候補: {n}", + "RunStep": "ステップ {i}/{n} · {s}", + "DetailLastRun": "{mode} · {t}", + "PkgInventory": "検査対象エントリ一覧 ({n})", + "EntriesOthers": "その他のエントリ (対象外): {n}", + "EntriesSummary": "対象: {n}", + "EntriesShowNonTargets": "対象外を表示 ({n})", + "EntriesRemapped": "再マップされたメソッドフィールド: {n}", + "LogRunStarted": "{mode}を開始 · 入力: {n}", + "LogScan": "スキャン完了: 候補 {n}、対象外スキップ {s}", + "LogInputStarted": "入力 {i}/{n}: {p}", + "LogCompanion": "コンパニオンを対応付け: {p}", + "LogStep": "ステップ {i}/{n}: {s}", + "LogEntry": "エントリ {p}: {o}", + "LogInputFinished": "完了: {o} ({t})", + "LogSummary": "復元済み {ok} · 要注意 {suspect} · 失敗 {failed} · スキップ {skipped}", + "AboutVersion": "バージョン {v}", + "TagMetadata": "il2cppメタデータ v{v}", + "web.unpack_tip": "選択した入力を復元します。結果はこのタブに保持され、ダウンロードできます。", + "web.unpack_desc": "復元します。結果はこのタブに保持され、ダウンロードできます。", + "web.download": "ダウンロード", + "web.download_all": "すべてダウンロード (.zip)", + "web.out_downloads": "ブラウザーのダウンロード", + "web.out_tip": "アンパック済みファイルの保存先です。", + "web.out_folder_help": "復元したファイルは、選択したフォルダー内の unpack/ に保存されます。ブラウザーで直接保存できないファイル(.dll など)は senbei-remaining.*.zip にまとめられます。ZIP を unpack/ に展開してください。", + "web.out_unsupported": "このブラウザーはフォルダーに書き込めないため、復元したファイルはダウンロードで保存します。", + "web.limit": "入力サイズの上限", + "web.limit_help": "上限を超える入力は読み込みません。復元中は、入力と復元イメージの両方をメモリ内に保持します。", + "web.over_limit": "この入力は{size}あり、入力サイズの上限{limit}を超えています。「設定」で上限を引き上げてから再実行してください。", + "web.engine_stopped": "復元エンジンが完了前に停止しました。この入力には、ブラウザーが確保できる以上のメモリが必要な可能性があります。", + "web.embedded_metadata": "埋め込みメタデータ", + "web.saved": "{path}に保存しました", + "web.save_failed": "{path}を保存できませんでした。", + "web.save_refused": "このブラウザーでは{name}をフォルダーに保存できません。ファイルはこのタブに保持され、ダウンロードできます。", + "web.read_failed": "この入力を読み込めませんでした。", +}; diff --git a/web/i18n/ko.js b/web/i18n/ko.js new file mode 100644 index 0000000..d38ce62 --- /dev/null +++ b/web/i18n/ko.js @@ -0,0 +1,268 @@ +// Generated by web/tools/gen-i18n.mjs from senbei-gui/src/text and +// web/i18n/web-strings.json. Edit the wording there and run the generator. +export default { + "tb.add_files": "파일 추가…", + "tb.add_folder": "폴더 추가…", + "tb.unpack": "언패킹", + "tb.unpack.all": "모두 언패킹", + "tb.output": "출력:", + "tb.settings": "설정", + "empty.title": "보호된 파일을 여기에 놓기", + "empty.folders": "폴더", + "empty.local": "모든 작업은 이 컴퓨터에서 실행됩니다. 입력은 절대 실행되거나 업로드되지 않습니다.", + "drag.title": "놓아서 추가", + "inputs.title": "입력", + "inputs.clear": "비우기", + "inputs.search": "이름으로 필터링", + "inputs.none": "필터와 일치하는 입력이 없습니다.", + "filter.all": "전체", + "filter.ok": "복원됨", + "filter.suspect": "주의 필요", + "filter.failed": "실패", + "filter.skipped": "건너뜀", + "group.files": "추가된 파일", + "mode.unpack": "언패킹됨", + "menu.copy_path": "경로 복사", + "menu.remove": "목록에서 제거", + "pending.not_run": "미실행", + "pending.not_protected": "보호되지 않음", + "pending.identified": "식별됨", + "pending.next": "수행할 작업", + "pending.not_protected_note": "Senbei가 이 파일에서 지원되는 보호를 찾지 못하여 복원할 내용이 없습니다.", + "scan.running": "스캔 중", + "scan.found": "현재까지 후보", + "run.running": "실행 중…", + "run.queued": "대기 중", + "run.will_not_run": "실행 안 함", + "run.stopping": "현재 입력 완료 후 중지 중…", + "run.cancel": "취소", + "run.progress": "진행 상태", + "run.cancelled_note": "이 입력에 도달하기 전에 작업이 취소되었습니다.", + "step.decrypt_header": "파일 헤더 복호화 중", + "step.decrypt_payload": "페이로드 복호화 중", + "step.locate_config": "구성 레이아웃 탐색 중", + "step.decrypt_stage2": "단계 2 복호화 중", + "step.decrypt_stages_3_5": "단계 3–5 복호화 중", + "step.decrypt_sections": "섹션 데이터 복호화 중", + "step.load_sections": "섹션 로드 및 압축 해제 중", + "step.decrypt_imports": "임포트 문자열 복호화 중", + "step.rebuild_headers": "PE 헤더 재구성 중", + "step.init_keys": "키 초기화 중", + "step.decrypt_key_table": "키 테이블 복호화 중", + "step.decrypt_primary": "기본 디스크립터 복호화 중", + "step.relocs_params": "재배치 및 압축 해제 매개변수 처리 중", + "step.decrypt_block1": "코드 블록 1 복호화 중", + "step.decrypt_block23": "코드 블록 2–3 복호화 중", + "step.decrypt_block4": "코드 블록 4 복호화 중", + "step.dll_sections": "섹션 복호화 및 압축 해제 중", + "step.fix_headers": "PE 헤더 및 섹션 테이블 보정 중", + "step.pe32_stages": "단계 복호화 중", + "step.pe32_eighth": "여덟 번째 단계 복호화 중", + "step.pe32_load": "파일 데이터 로드 및 압축 해제 중", + "step.pe32_text": ".text 복호화 중", + "step.pe32_text_skip": ".text 건너뛰는 중 (이미 평문)", + "step.pe32_rebuild": "PE 파일 레이아웃 재구성 중", + "step.android_primary": "기본 컨테이너 디코딩 중", + "step.android_aux": "ELF 재구성 컨테이너 디코딩 중", + "step.android_tables": "동적 링커 테이블 재구성 중", + "detail.pick": "왼쪽에서 입력 또는 그룹을 선택하세요.", + "detail.export_json": "JSON 내보내기", + "detail.export_text": "텍스트 내보내기", + "detail.copy": "복사", + "detail.technical": "기술 세부 정보", + "companion.spliced_pill": "컴패니언 파일 연결됨", + "tab.overview": "개요", + "tab.log": "로그", + "tab.entries": "항목", + "batch.summary": "요약", + "batch.inputs": "입력", + "batch.scan": "폴더 스캔", + "batch.non_target": "건너뛴 비대상 파일", + "batch.walk_errors": "읽을 수 없는 폴더 항목", + "batch.probe_errors": "프로브 오류", + "batch.scan_note": "폴더를 스캔할 때 .exe, .dll, .so, global-metadata.dat 및 Android 앱 패키지를 검사합니다.", + "batch.scan_incomplete": "분석이 불완전합니다: 일부 폴더 항목 또는 선택한 파일을 조사할 수 없었습니다.", + "pkg.title": "패키지", + "pkg.kind": "패키지 유형", + "pkg.package": "패키지 이름", + "pkg.version": "버전", + "pkg.entries": "최상위 항목", + "pkg.candidates": "프로브할 항목", + "pkg.nested": "중첩 패키지", + "pkg.note": ".so 및 global-metadata.dat 항목만 추출하여 프로브합니다.", + "pkg.result": "결과", + "pkg.manifests": "매니페스트", + "pkg.unnamed": "이름 없음", + "pkg.targets": "보호된 항목 및 메타데이터", + "pkg.no_targets": "이 패키지에 보호된 항목이 없으므로 복원할 내용이 없습니다.", + "entries.title": "항목", + "entries.remapped_label": "재매핑된 메서드 필드", + "col.name": "이름", + "col.type": "유형", + "col.outcome": "결과", + "col.route": "경로", + "col.time": "시간", + "col.source": "소스", + "col.status": "상태", + "common.yes": "예", + "common.no": "아니요", + "ov.messages": "메시지", + "ov.recognition": "인식", + "ov.platform": "플랫폼", + "ov.format": "형식", + "ov.kind": "종류", + "ov.metadata": "il2cpp 메타데이터", + "ov.metadata_version": "메타데이터 버전", + "ov.metadata_layout": "레이아웃 정의", + "ov.cap_seeded": "시드 기반 메서드 토큰", + "ov.cap_structural": "구조적 메서드 토큰", + "ov.cap_indices": "메서드 인덱스 복원", + "ov.cap_context": "애플리케이션 컨텍스트 필요", + "ov.evidence": "근거", + "ov.no_evidence": "보호 근거 없음", + "ov.routes": "복원 경로", + "ov.selected": "선택됨", + "ov.no_routes": "시도된 경로가 없습니다.", + "ov.stages": "단계", + "ov.validation": "정적 검증", + "ov.validation_metadata": "이 정적 검증은 PE와 ELF 구조를 검사합니다. 메타데이터 테이블은 변환 과정에서 검증합니다.", + "ov.validation_warnings": "복원된 이미지에서 구조적 문제가 발견되어 정상 실행되지 않을 수 있습니다. '주의 필요'로 분류되지만 언패킹 시 파일은 그대로 저장됩니다.", + "ov.validation_failed": "정적 검증에서 복원 이미지의 치명적인 구조 오류가 발견되어 실행되지 않을 가능성이 높습니다. '주의 필요'로 분류되지만 언패킹 시 파일은 그대로 저장됩니다.", + "ov.identity": "식별 정보", + "ov.source": "입력", + "ov.companion": "컴패니언 파일", + "ov.recovered": "복원된 이미지", + "ov.output": "출력", + "ov.restored_elf": "복원된 ELF", + "ov.elf_sections": "섹션 · 세그먼트", + "ov.elf_symbols": "동적 심볼", + "ov.elf_relocs": "재배치 · PLT", + "log.f_all": "전체", + "log.f_nosteps": "단계 숨기기", + "log.f_problems": "문제만", + "log.copy": "로그 복사", + "log.lv_info": "INFO", + "log.lv_step": "STEP", + "log.lv_warn": "WARN", + "log.lv_error": "ERROR", + "status.ready": "준비", + "legal.title": "법적 고지: 사용 전 필독", + "legal.p1": "Senbei는 이미 적법하게 보유한 소프트웨어의 합법적인 리버스 엔지니어링, 보안 연구 및 보존을 위한 연구 및 상호운용성 도구입니다. 본인이 소유하거나 분석할 명시적 권한이 있는 바이너리만 처리하십시오.", + "legal.p2": "기술적 보호 조치를 우회하는 행위는 관할권에 따라 제한될 수 있습니다(예: 보안 연구 및 상호운용성에 대한 예외 조항을 포함하는 미국 DMCA §1201). 사용의 적법성을 보장하는 것은 사용자 본인의 책임입니다.", + "legal.p3": "Senbei는 컴퓨터의 파일에 대해 순수하게 정적인 변환만 수행합니다. 자체적으로 접근 통제를 우회하지 않고, 필요한 정보를 입력 파일에서 도출하며, 벤더 코드를 포함하지 않고, 입력을 절대 실행하거나 업로드하지 않습니다. 한 Android 패키징 변형의 내장 메타데이터 계층은 단일 빌드 분석 중 복원된 XOR 키스트림으로 해제되며, 해당 키스트림은 도구와 함께 제공되는 연구 산출물이지 벤더가 배포한 키가 아닙니다.", + "legal.p4": "Senbei는 온라인 플레이, 라이선스 사기 또는 부정행위를 가능하게 하지 않습니다. 복호화된 출력을 재배포하거나 어디에도 업로드하지 마십시오. 이 소프트웨어는 어떠한 종류의 보증도 없이 “있는 그대로” 제공되며, 작성자는 오용에 대해 어떠한 책임도 지지 않습니다. “CrackProof”는 해당 소유자의 상표이며, 이 프로젝트는 벤더나 어떠한 퍼블리셔와도 제휴하거나 보증받지 않았습니다.", + "legal.accept": "이해했으며 동의합니다", + "settings.title": "설정", + "settings.tab_general": "일반", + "settings.tab_memory": "메모리", + "settings.tab_about": "정보", + "settings.language": "언어", + "settings.output": "기본 출력 폴더", + "settings.output_recent": "최근 사용한 폴더", + "settings.output_choose": "폴더 선택…", + "settings.reset": "기본값으로 재설정", + "settings.done": "완료", + "about.desc": "CrackProof로 보호된 Windows PE 파일 및 Android AArch64 공유 라이브러리용 정적 언패커입니다.", + "about.license": "라이선스", + "about.source": "소스 코드", + "about.legal": "법적 고지 표시", + "status.ok": "복원됨", + "status.suspect": "주의 필요", + "status.skipped": "건너뜀", + "status.error": "오류", + "status.incomplete": "분석 미완료", + "entryStatus.restored": "복원됨", + "entryStatus.not_target": "대상 아님", + "entryStatus.unchanged": "변경 없음", + "entryStatus.error": "오류", + "entryKind.shared_library": "공유 라이브러리", + "entryKind.metadata": "il2cpp 메타데이터", + "recognition.not_attempted": "시도 안 함", + "recognition.recognized": "인식됨", + "recognition.not_recognized": "인식되지 않음", + "recognition.blocked": "차단됨", + "outcome.succeeded": "성공", + "outcome.rejected": "거부됨", + "outcome.failed": "실패", + "outcome.not_attempted": "시도 안 함", + "validation.clean": "정상", + "validation.warnings": "경고", + "validation.failed": "실패", + "validation.not_run": "미실행", + "stage.detection": "탐지", + "stage.recovery": "복원", + "stage.static_validation": "정적 검증", + "stage.output_write": "출력 기록", + "stageStatus.ok": "정상", + "stageStatus.skipped": "건너뜀", + "stageStatus.failed": "실패", + "stageStatus.blocked": "차단됨", + "evidence.header_magic": "헤더 매직", + "evidence.companion_spliced": "컴패니언 파일 결합됨", + "evidence.external_companion_declaration": "외부 컴패니언 파일 선언", + "evidence.private_section": "전용 섹션", + "evidence.aes_schedule": "AES 키 스케줄", + "evidence.validated_metadata_transform": "검증된 메타데이터 변환", + "platform.windows_pe": "Windows PE", + "platform.android_elf": "Android ELF", + "platform.il2cpp_metadata": "il2cpp 메타데이터", + "kind.native_exe": "네이티브 실행 파일", + "kind.managed_exe": ".NET 실행 파일", + "kind.native_dll": "네이티브 DLL", + "kind.managed_dll": ".NET 어셈블리 (DLL)", + "kindShort.native_exe": "EXE", + "kindShort.managed_exe": ".NET EXE", + "kindShort.native_dll": "DLL", + "kindShort.managed_dll": ".NET DLL", + "layout.exe_style": "EXE 스타일 로더", + "layout.dll": "DLL 로더", + "layout.android_staged": "Android 단계별 로더", + "layout.metadata_seeded": "시드 기반 메타데이터 변환", + "layout.metadata_structural": "구조적 메타데이터 변환", + "layout.metadata_method_indices": "메타데이터 메서드 인덱스 복원", + "metaLayout.known": "알려짐", + "metaLayout.context_required": "애플리케이션 컨텍스트 필요", + "metaLayout.unverified": "미검증", + "companion.absent": "없음", + "companion.spliced": "결합됨", + "companion.paired": "연결됨", + "companion.unmatched": "일치하지 않음", + "companion.unreadable": "읽을 수 없음", + "TbUnpackN": "언패킹 ({n})", + "GroupScanning": "스캔 중… 현재까지 후보: {n}", + "ScanStatus": "{p} 스캔 중… 현재까지 후보: {n}", + "RunStep": "단계 {i}/{n} · {s}", + "DetailLastRun": "{mode} · {t}", + "PkgInventory": "검사 대상 항목 목록 ({n})", + "EntriesOthers": "기타 항목 (대상 아님): {n}", + "EntriesSummary": "대상: {n}", + "EntriesShowNonTargets": "비대상 항목 표시 ({n})", + "EntriesRemapped": "재매핑된 메서드 필드: {n}", + "LogRunStarted": "{mode} 시작됨 · 입력: {n}", + "LogScan": "스캔 완료: 후보 {n}, 건너뛴 비대상 {s}", + "LogInputStarted": "입력 {i}/{n}: {p}", + "LogCompanion": "컴패니언 파일 연결됨: {p}", + "LogStep": "단계 {i}/{n}: {s}", + "LogEntry": "항목 {p}: {o}", + "LogInputFinished": "완료: {o} ({t})", + "LogSummary": "복원됨 {ok} · 주의 필요 {suspect} · 실패 {failed} · 건너뜀 {skipped}", + "AboutVersion": "버전 {v}", + "TagMetadata": "il2cpp 메타데이터 v{v}", + "web.unpack_tip": "선택한 입력을 복원합니다. 결과는 이 탭에 보관되며 다운로드할 수 있습니다.", + "web.unpack_desc": "복원합니다. 결과는 이 탭에 보관되며 다운로드할 수 있습니다.", + "web.download": "다운로드", + "web.download_all": "모두 다운로드 (.zip)", + "web.out_downloads": "브라우저 다운로드", + "web.out_tip": "언패킹된 파일을 저장할 위치입니다.", + "web.out_folder_help": "복원된 파일은 선택한 폴더 안의 unpack/에 저장됩니다. 브라우저에서 직접 저장할 수 없는 파일(예: .dll)은 senbei-remaining.*.zip에 담깁니다. ZIP 파일을 unpack/에 풀어 주세요.", + "web.out_unsupported": "이 브라우저는 폴더에 기록할 수 없으므로 복원된 파일은 다운로드로 저장합니다.", + "web.limit": "입력 크기 제한", + "web.limit_help": "제한을 초과하는 입력은 읽지 않습니다. 복원 중에는 입력과 복원된 이미지를 함께 메모리에 유지합니다.", + "web.over_limit": "이 입력은 {size}로 입력 크기 제한 {limit}을(를) 초과합니다. 설정에서 제한을 높인 후 다시 실행하십시오.", + "web.engine_stopped": "복원 엔진이 완료 전에 중지되었습니다. 이 입력에는 브라우저가 제공할 수 있는 것보다 많은 메모리가 필요할 수 있습니다.", + "web.embedded_metadata": "내장 메타데이터", + "web.saved": "{path}에 저장됨", + "web.save_failed": "{path}을(를) 저장할 수 없습니다.", + "web.save_refused": "이 브라우저에서는 {name}을(를) 폴더에 저장할 수 없습니다. 파일은 이 탭에 보관되며 다운로드할 수 있습니다.", + "web.read_failed": "이 입력을 읽을 수 없습니다.", +}; diff --git a/web/i18n/web-strings.json b/web/i18n/web-strings.json new file mode 100644 index 0000000..efc0b3f --- /dev/null +++ b/web/i18n/web-strings.json @@ -0,0 +1,121 @@ +{ + "web.unpack_tip": { + "en": "Recover the selected inputs. Results are kept in this tab for download.", + "zh-CN": "恢复选中的输入项。结果保留在此标签页中,可随时下载。", + "zh-TW": "恢復所選輸入項。結果會保留在此分頁中,可隨時下載。", + "ja": "選択した入力を復元します。結果はこのタブに保持され、ダウンロードできます。", + "ko": "선택한 입력을 복원합니다. 결과는 이 탭에 보관되며 다운로드할 수 있습니다." + }, + "web.unpack_desc": { + "en": "Recover it. The result is kept in this tab for download.", + "zh-CN": "恢复该项。结果保留在此标签页中,可随时下载。", + "zh-TW": "進行恢復。結果會保留在此分頁中,可隨時下載。", + "ja": "復元します。結果はこのタブに保持され、ダウンロードできます。", + "ko": "복원합니다. 결과는 이 탭에 보관되며 다운로드할 수 있습니다." + }, + "web.download": { + "en": "Download", + "zh-CN": "下载", + "zh-TW": "下載", + "ja": "ダウンロード", + "ko": "다운로드" + }, + "web.download_all": { + "en": "Download all (.zip)", + "zh-CN": "全部下载 (.zip)", + "zh-TW": "全部下載 (.zip)", + "ja": "すべてダウンロード (.zip)", + "ko": "모두 다운로드 (.zip)" + }, + "web.out_downloads": { + "en": "Browser download", + "zh-CN": "浏览器下载", + "zh-TW": "瀏覽器下載", + "ja": "ブラウザーのダウンロード", + "ko": "브라우저 다운로드" + }, + "web.out_tip": { + "en": "Where unpacked files are saved.", + "zh-CN": "解包后文件的保存位置。", + "zh-TW": "解包後檔案的儲存位置。", + "ja": "アンパック済みファイルの保存先です。", + "ko": "언패킹된 파일을 저장할 위치입니다." + }, + "web.out_folder_help": { + "en": "When you choose a folder, Senbei saves to unpack/ inside it. Files the browser won’t save directly (such as .dll files) go into senbei-remaining.*.zip. Extract it into unpack/.", + "zh-CN": "Senbei 会将文件保存到所选文件夹下的 unpack/。如果浏览器不允许直接保存某些文件(如 .dll),这些文件会打包到 senbei-remaining.*.zip 中。请将压缩包解压到 unpack/。", + "zh-TW": "Senbei 會將檔案儲存到所選資料夾下的 unpack/。如果瀏覽器不允許直接儲存某些檔案(例如 .dll),這些檔案會打包成 senbei-remaining.*.zip。請將 ZIP 解壓縮到 unpack/。", + "ja": "復元したファイルは、選択したフォルダー内の unpack/ に保存されます。ブラウザーで直接保存できないファイル(.dll など)は senbei-remaining.*.zip にまとめられます。ZIP を unpack/ に展開してください。", + "ko": "복원된 파일은 선택한 폴더 안의 unpack/에 저장됩니다. 브라우저에서 직접 저장할 수 없는 파일(예: .dll)은 senbei-remaining.*.zip에 담깁니다. ZIP 파일을 unpack/에 풀어 주세요." + }, + "web.out_unsupported": { + "en": "This browser cannot write to a folder, so recovered files are saved as downloads.", + "zh-CN": "此浏览器无法写入文件夹,恢复后的文件只能通过下载保存。", + "zh-TW": "此瀏覽器無法寫入資料夾,復原後的檔案只能透過下載儲存。", + "ja": "このブラウザーはフォルダーに書き込めないため、復元したファイルはダウンロードで保存します。", + "ko": "이 브라우저는 폴더에 기록할 수 없으므로 복원된 파일은 다운로드로 저장합니다." + }, + "web.limit": { + "en": "Input size limit", + "zh-CN": "输入大小上限", + "zh-TW": "輸入大小上限", + "ja": "入力サイズの上限", + "ko": "입력 크기 제한" + }, + "web.limit_help": { + "en": "Larger inputs are not read. Recovery keeps the input and the restored image in memory at the same time.", + "zh-CN": "超过上限的输入项不会被读取。恢复过程中,输入项与恢复后的映像会同时保留在内存中。", + "zh-TW": "超過上限的輸入項不會被讀取。恢復過程中,輸入項與復原後的映像會同時保留在記憶體中。", + "ja": "上限を超える入力は読み込みません。復元中は、入力と復元イメージの両方をメモリ内に保持します。", + "ko": "제한을 초과하는 입력은 읽지 않습니다. 복원 중에는 입력과 복원된 이미지를 함께 메모리에 유지합니다." + }, + "web.over_limit": { + "en": "This input is {size}, over the {limit} input size limit. Raise the limit in Settings, then run it again.", + "zh-CN": "该输入项为 {size},超出 {limit} 的输入大小上限。请在“设置”中调高上限后重新运行。", + "zh-TW": "此輸入項為 {size},超過 {limit} 的輸入大小上限。請在「設定」中調高上限,然後重新執行。", + "ja": "この入力は{size}あり、入力サイズの上限{limit}を超えています。「設定」で上限を引き上げてから再実行してください。", + "ko": "이 입력은 {size}로 입력 크기 제한 {limit}을(를) 초과합니다. 설정에서 제한을 높인 후 다시 실행하십시오." + }, + "web.engine_stopped": { + "en": "The recovery engine stopped before finishing. This input may need more memory than the browser can provide.", + "zh-CN": "恢复引擎在完成前意外停止。该输入项所需的内存可能超出了此浏览器的上限。", + "zh-TW": "恢復引擎在完成前意外停止。此輸入項所需的記憶體可能超出此瀏覽器的上限。", + "ja": "復元エンジンが完了前に停止しました。この入力には、ブラウザーが確保できる以上のメモリが必要な可能性があります。", + "ko": "복원 엔진이 완료 전에 중지되었습니다. 이 입력에는 브라우저가 제공할 수 있는 것보다 많은 메모리가 필요할 수 있습니다." + }, + "web.embedded_metadata": { + "en": "Embedded metadata", + "zh-CN": "内嵌元数据", + "zh-TW": "內嵌中繼資料", + "ja": "埋め込みメタデータ", + "ko": "내장 메타데이터" + }, + "web.saved": { + "en": "Saved to {path}", + "zh-CN": "已保存到 {path}", + "zh-TW": "已儲存至 {path}", + "ja": "{path}に保存しました", + "ko": "{path}에 저장됨" + }, + "web.save_failed": { + "en": "Could not save {path}.", + "zh-CN": "无法保存 {path}。", + "zh-TW": "無法儲存 {path}。", + "ja": "{path}を保存できませんでした。", + "ko": "{path}을(를) 저장할 수 없습니다." + }, + "web.save_refused": { + "en": "This browser does not allow saving {name} to a folder. It is kept in this tab for download.", + "zh-CN": "此浏览器不允许将 {name} 保存到文件夹。该文件已保留在此标签页中,可随时下载。", + "zh-TW": "此瀏覽器不允許將 {name} 儲存至資料夾。檔案已保留在此分頁中,可隨時下載。", + "ja": "このブラウザーでは{name}をフォルダーに保存できません。ファイルはこのタブに保持され、ダウンロードできます。", + "ko": "이 브라우저에서는 {name}을(를) 폴더에 저장할 수 없습니다. 파일은 이 탭에 보관되며 다운로드할 수 있습니다." + }, + "web.read_failed": { + "en": "Could not read this input.", + "zh-CN": "无法读取该输入项。", + "zh-TW": "無法讀取此輸入項。", + "ja": "この入力を読み込めませんでした。", + "ko": "이 입력을 읽을 수 없습니다." + } +} diff --git a/web/i18n/zh-CN.js b/web/i18n/zh-CN.js new file mode 100644 index 0000000..f9f16bd --- /dev/null +++ b/web/i18n/zh-CN.js @@ -0,0 +1,268 @@ +// Generated by web/tools/gen-i18n.mjs from senbei-gui/src/text and +// web/i18n/web-strings.json. Edit the wording there and run the generator. +export default { + "tb.add_files": "添加文件…", + "tb.add_folder": "添加文件夹…", + "tb.unpack": "解包", + "tb.unpack.all": "全部解包", + "tb.output": "输出:", + "tb.settings": "设置", + "empty.title": "将受保护文件拖放到此处", + "empty.folders": "文件夹", + "empty.local": "所有操作均在本机运行。输入项绝不会被执行或上传。", + "drag.title": "松开以添加", + "inputs.title": "输入项", + "inputs.clear": "清空", + "inputs.search": "按名称筛选", + "inputs.none": "没有匹配筛选条件的输入项。", + "filter.all": "全部", + "filter.ok": "已恢复", + "filter.suspect": "可疑", + "filter.failed": "失败", + "filter.skipped": "已跳过", + "group.files": "已添加的文件", + "mode.unpack": "已解包", + "menu.copy_path": "复制路径", + "menu.remove": "从列表中移除", + "pending.not_run": "尚未运行", + "pending.not_protected": "未受保护", + "pending.identified": "已识别", + "pending.next": "可执行的操作", + "pending.not_protected_note": "未在此文件中检测到受支持的保护。", + "scan.running": "正在扫描", + "scan.found": "当前候选", + "run.running": "正在运行…", + "run.queued": "排队中", + "run.will_not_run": "不会运行", + "run.stopping": "将在当前输入项完成后停止…", + "run.cancel": "取消", + "run.progress": "进度", + "run.cancelled_note": "任务在处理到此输入项前已取消。", + "step.decrypt_header": "正在解密文件头部", + "step.decrypt_payload": "正在解密载荷", + "step.locate_config": "正在定位配置布局", + "step.decrypt_stage2": "正在解密阶段 2", + "step.decrypt_stages_3_5": "正在解密阶段 3–5", + "step.decrypt_sections": "正在解密节数据", + "step.load_sections": "正在加载并解压各节", + "step.decrypt_imports": "正在解密导入字符串", + "step.rebuild_headers": "正在重建 PE 头部", + "step.init_keys": "正在初始化密钥", + "step.decrypt_key_table": "正在解密密钥表", + "step.decrypt_primary": "正在解密主描述符", + "step.relocs_params": "正在处理重定位与解压参数", + "step.decrypt_block1": "正在解密代码块 1", + "step.decrypt_block23": "正在解密代码块 2–3", + "step.decrypt_block4": "正在解密代码块 4", + "step.dll_sections": "正在解密并解压各节", + "step.fix_headers": "正在修正 PE 头部与节表", + "step.pe32_stages": "正在解密各阶段", + "step.pe32_eighth": "正在解密第八阶段", + "step.pe32_load": "正在加载并解压文件数据", + "step.pe32_text": "正在解密 .text", + "step.pe32_text_skip": "正在跳过 .text(已是明文)", + "step.pe32_rebuild": "正在重建 PE 文件布局", + "step.android_primary": "正在解码主容器", + "step.android_aux": "正在解码辅助 ELF 容器", + "step.android_tables": "正在重建动态链接器表", + "detail.pick": "请在左侧选择一个输入项或分组。", + "detail.export_json": "导出 JSON", + "detail.export_text": "导出文本", + "detail.copy": "复制", + "detail.technical": "技术细节", + "companion.spliced_pill": "已配对伴生文件", + "tab.overview": "概览", + "tab.log": "日志", + "tab.entries": "条目", + "batch.summary": "汇总", + "batch.inputs": "输入项", + "batch.scan": "文件夹扫描", + "batch.non_target": "已跳过非目标", + "batch.walk_errors": "无法读取的目录项", + "batch.probe_errors": "探测错误", + "batch.scan_note": "文件夹扫描会检查 .exe、.dll、.so、global-metadata.dat 和 Android 应用包。", + "batch.scan_incomplete": "分析不完整:部分目录项或所选文件无法读取或检查。", + "pkg.title": "应用包", + "pkg.kind": "应用包类型", + "pkg.package": "包名", + "pkg.version": "版本", + "pkg.entries": "顶层条目", + "pkg.candidates": "待探测条目", + "pkg.nested": "嵌套应用包", + "pkg.note": "仅提取并探测 .so 与 global-metadata.dat 条目。", + "pkg.result": "结果", + "pkg.manifests": "清单", + "pkg.unnamed": "未命名", + "pkg.targets": "受保护条目与元数据", + "pkg.no_targets": "此应用包中没有受保护的条目,无需恢复。", + "entries.title": "条目", + "entries.remapped_label": "已重映射方法字段", + "col.name": "名称", + "col.type": "类型", + "col.outcome": "结果", + "col.route": "方案", + "col.time": "用时", + "col.source": "来源", + "col.status": "状态", + "common.yes": "是", + "common.no": "否", + "ov.messages": "消息", + "ov.recognition": "识别", + "ov.platform": "平台", + "ov.format": "格式", + "ov.kind": "种类", + "ov.metadata": "il2cpp 元数据", + "ov.metadata_version": "元数据版本", + "ov.metadata_layout": "布局定义", + "ov.cap_seeded": "基于种子的方法令牌", + "ov.cap_structural": "结构化方法令牌", + "ov.cap_indices": "方法索引恢复", + "ov.cap_context": "需要应用上下文", + "ov.evidence": "依据", + "ov.no_evidence": "无保护依据", + "ov.routes": "恢复方案", + "ov.selected": "已选用", + "ov.no_routes": "未尝试任何恢复方案。", + "ov.stages": "阶段", + "ov.validation": "静态验证", + "ov.validation_metadata": "此处的静态验证针对 PE 和 ELF。元数据表结构会在转换流程中校验。", + "ov.validation_warnings": "恢复后的映像存在结构问题,可能无法运行。结果标记为“可疑”,解包时仍会保存文件。", + "ov.validation_failed": "静态验证发现恢复后的映像存在致命结构错误,很可能无法运行。结果标记为“可疑”,解包时仍会保存文件。", + "ov.identity": "标识信息", + "ov.source": "输入项", + "ov.companion": "伴生文件", + "ov.recovered": "恢复映像", + "ov.output": "输出", + "ov.restored_elf": "已恢复的 ELF", + "ov.elf_sections": "节 · 段", + "ov.elf_symbols": "动态符号", + "ov.elf_relocs": "重定位 · PLT", + "log.f_all": "全部", + "log.f_nosteps": "隐藏步骤", + "log.f_problems": "仅问题", + "log.copy": "复制日志", + "log.lv_info": "INFO", + "log.lv_step": "STEP", + "log.lv_warn": "WARN", + "log.lv_error": "ERROR", + "status.ready": "就绪", + "legal.title": "法律声明:使用前请阅读", + "legal.p1": "Senbei 是一款用于研究与互操作性的工具,用于对你已合法拥有的软件进行合法的逆向工程、安全研究与保存。请仅处理你拥有或已获明确授权分析的二进制文件。", + "legal.p2": "规避技术保护措施在你所在的司法管辖区可能受到限制(例如美国 DMCA §1201 的规定,其中包含针对安全研究与互操作性的豁免条款)。确保使用行为合法是你本人的责任。", + "legal.p3": "Senbei 在你的计算机上对文件执行纯静态转换:它本身不绕过任何访问控制,所需内容均从输入文件中推导,不包含任何厂商代码,且绝不执行或上传其输入项。某一种 Android 打包变体的内嵌元数据层使用在分析单个构建版本时恢复出的 XOR 密钥流解封;该密钥流是随工具附带的研究成果,而非厂商分发的密钥。", + "legal.p4": "Senbei 不提供联机游戏、授权欺诈或作弊功能。请勿二次分发解密后的输出或将其上传至任何地方。本软件按“原样”提供,不附带任何形式的担保;作者对滥用行为不承担任何责任。“CrackProof”是其所有者的商标;本项目与该厂商或任何发行商均无关联,亦未获得其背书。", + "legal.accept": "我已理解并接受", + "settings.title": "设置", + "settings.tab_general": "常规", + "settings.tab_memory": "内存", + "settings.tab_about": "关于", + "settings.language": "语言", + "settings.output": "默认输出文件夹", + "settings.output_recent": "上次使用的文件夹", + "settings.output_choose": "选择文件夹…", + "settings.reset": "恢复默认设置", + "settings.done": "完成", + "about.desc": "适用于受 CrackProof 保护的 Windows PE 文件与 Android AArch64 共享库的静态解包工具。", + "about.license": "许可证", + "about.source": "源代码", + "about.legal": "显示法律声明", + "status.ok": "已恢复", + "status.suspect": "可疑", + "status.skipped": "已跳过", + "status.error": "错误", + "status.incomplete": "分析不完整", + "entryStatus.restored": "已恢复", + "entryStatus.not_target": "非目标", + "entryStatus.unchanged": "未更改", + "entryStatus.error": "错误", + "entryKind.shared_library": "共享库", + "entryKind.metadata": "il2cpp 元数据", + "recognition.not_attempted": "未尝试", + "recognition.recognized": "已识别", + "recognition.not_recognized": "未识别", + "recognition.blocked": "受阻", + "outcome.succeeded": "成功", + "outcome.rejected": "已拒绝", + "outcome.failed": "失败", + "outcome.not_attempted": "未尝试", + "validation.clean": "通过", + "validation.warnings": "警告", + "validation.failed": "失败", + "validation.not_run": "未运行", + "stage.detection": "检测", + "stage.recovery": "恢复", + "stage.static_validation": "静态验证", + "stage.output_write": "输出写入", + "stageStatus.ok": "正常", + "stageStatus.skipped": "已跳过", + "stageStatus.failed": "失败", + "stageStatus.blocked": "受阻", + "evidence.header_magic": "头部魔数", + "evidence.companion_spliced": "已拼接伴生文件", + "evidence.external_companion_declaration": "声明了外部伴生文件", + "evidence.private_section": "私有节", + "evidence.aes_schedule": "AES 密钥编排表", + "evidence.validated_metadata_transform": "已验证的元数据变换", + "platform.windows_pe": "Windows PE", + "platform.android_elf": "Android ELF", + "platform.il2cpp_metadata": "il2cpp 元数据", + "kind.native_exe": "原生可执行文件", + "kind.managed_exe": ".NET 可执行文件", + "kind.native_dll": "原生 DLL", + "kind.managed_dll": ".NET 程序集 (DLL)", + "kindShort.native_exe": "EXE", + "kindShort.managed_exe": ".NET EXE", + "kindShort.native_dll": "DLL", + "kindShort.managed_dll": ".NET DLL", + "layout.exe_style": "EXE 风格加载器", + "layout.dll": "DLL 加载器", + "layout.android_staged": "Android 分阶段加载器", + "layout.metadata_seeded": "基于种子的元数据变换", + "layout.metadata_structural": "结构化元数据变换", + "layout.metadata_method_indices": "元数据方法索引恢复", + "metaLayout.known": "已知", + "metaLayout.context_required": "需要应用上下文", + "metaLayout.unverified": "未验证", + "companion.absent": "无", + "companion.spliced": "已拼接", + "companion.paired": "已配对", + "companion.unmatched": "不匹配", + "companion.unreadable": "不可读", + "TbUnpackN": "解包 ({n})", + "GroupScanning": "正在扫描… 当前候选:{n}", + "ScanStatus": "正在扫描 {p}… 当前候选:{n}", + "RunStep": "步骤 {i}/{n} · {s}", + "DetailLastRun": "{mode} · {t}", + "PkgInventory": "候选条目:{n}", + "EntriesOthers": "其他条目(非目标):{n}", + "EntriesSummary": "目标:{n}", + "EntriesShowNonTargets": "显示非目标 ({n})", + "EntriesRemapped": "已重映射方法字段:{n}", + "LogRunStarted": "{mode}已开始 · 输入项:{n}", + "LogScan": "扫描完成:候选 {n},已跳过非目标 {s}", + "LogInputStarted": "输入项 {i}/{n}:{p}", + "LogCompanion": "已配对伴生文件:{p}", + "LogStep": "步骤 {i}/{n}:{s}", + "LogEntry": "条目 {p}:{o}", + "LogInputFinished": "已完成:{o} ({t})", + "LogSummary": "已恢复 {ok} · 可疑 {suspect} · 失败 {failed} · 已跳过 {skipped}", + "AboutVersion": "版本 {v}", + "TagMetadata": "il2cpp 元数据 v{v}", + "web.unpack_tip": "恢复选中的输入项。结果保留在此标签页中,可随时下载。", + "web.unpack_desc": "恢复该项。结果保留在此标签页中,可随时下载。", + "web.download": "下载", + "web.download_all": "全部下载 (.zip)", + "web.out_downloads": "浏览器下载", + "web.out_tip": "解包后文件的保存位置。", + "web.out_folder_help": "Senbei 会将文件保存到所选文件夹下的 unpack/。如果浏览器不允许直接保存某些文件(如 .dll),这些文件会打包到 senbei-remaining.*.zip 中。请将压缩包解压到 unpack/。", + "web.out_unsupported": "此浏览器无法写入文件夹,恢复后的文件只能通过下载保存。", + "web.limit": "输入大小上限", + "web.limit_help": "超过上限的输入项不会被读取。恢复过程中,输入项与恢复后的映像会同时保留在内存中。", + "web.over_limit": "该输入项为 {size},超出 {limit} 的输入大小上限。请在“设置”中调高上限后重新运行。", + "web.engine_stopped": "恢复引擎在完成前意外停止。该输入项所需的内存可能超出了此浏览器的上限。", + "web.embedded_metadata": "内嵌元数据", + "web.saved": "已保存到 {path}", + "web.save_failed": "无法保存 {path}。", + "web.save_refused": "此浏览器不允许将 {name} 保存到文件夹。该文件已保留在此标签页中,可随时下载。", + "web.read_failed": "无法读取该输入项。", +}; diff --git a/web/i18n/zh-TW.js b/web/i18n/zh-TW.js new file mode 100644 index 0000000..22eb332 --- /dev/null +++ b/web/i18n/zh-TW.js @@ -0,0 +1,268 @@ +// Generated by web/tools/gen-i18n.mjs from senbei-gui/src/text and +// web/i18n/web-strings.json. Edit the wording there and run the generator. +export default { + "tb.add_files": "加入檔案…", + "tb.add_folder": "加入資料夾…", + "tb.unpack": "解包", + "tb.unpack.all": "全部解包", + "tb.output": "輸出:", + "tb.settings": "設定", + "empty.title": "將受保護檔案拖放至此", + "empty.folders": "資料夾", + "empty.local": "所有處理均在本機執行。輸入檔案絕不會被執行或上傳。", + "drag.title": "放開以加入", + "inputs.title": "輸入項", + "inputs.clear": "清除", + "inputs.search": "依名稱篩選", + "inputs.none": "沒有符合篩選條件的輸入項。", + "filter.all": "全部", + "filter.ok": "已恢復", + "filter.suspect": "可疑", + "filter.failed": "失敗", + "filter.skipped": "已略過", + "group.files": "已加入的檔案", + "mode.unpack": "已解包", + "menu.copy_path": "複製路徑", + "menu.remove": "從清單移除", + "pending.not_run": "尚未執行", + "pending.not_protected": "未受保護", + "pending.identified": "已識別", + "pending.next": "後續操作", + "pending.not_protected_note": "未在此檔案中偵測到受支援的保護。", + "scan.running": "掃描中", + "scan.found": "目前候選", + "run.running": "執行中…", + "run.queued": "佇列中", + "run.will_not_run": "不會執行", + "run.stopping": "將在目前輸入項完成後停止…", + "run.cancel": "取消", + "run.progress": "進度", + "run.cancelled_note": "工作在處理到此輸入項之前已取消。", + "step.decrypt_header": "解密檔案標頭", + "step.decrypt_payload": "解密載荷", + "step.locate_config": "尋找設定結構", + "step.decrypt_stage2": "解密階段 2", + "step.decrypt_stages_3_5": "解密階段 3–5", + "step.decrypt_sections": "解密節區資料", + "step.load_sections": "載入並解壓縮節區", + "step.decrypt_imports": "解密匯入字串", + "step.rebuild_headers": "重建 PE 標頭", + "step.init_keys": "初始化金鑰", + "step.decrypt_key_table": "解密金鑰表", + "step.decrypt_primary": "解密主要描述元", + "step.relocs_params": "處理重定位與解壓縮參數", + "step.decrypt_block1": "解密程式碼區塊 1", + "step.decrypt_block23": "解密程式碼區塊 2–3", + "step.decrypt_block4": "解密程式碼區塊 4", + "step.dll_sections": "解密並解壓縮節區", + "step.fix_headers": "修補 PE 標頭與節區表", + "step.pe32_stages": "解密各階段", + "step.pe32_eighth": "解密第 8 階段", + "step.pe32_load": "載入並解壓縮檔案資料", + "step.pe32_text": "解密 .text", + "step.pe32_text_skip": "略過 .text(已為明文)", + "step.pe32_rebuild": "重建 PE 檔案配置", + "step.android_primary": "解碼主要容器", + "step.android_aux": "解碼輔助 ELF 容器", + "step.android_tables": "重建動態連結器表", + "detail.pick": "請在左側選取輸入項或群組。", + "detail.export_json": "匯出 JSON", + "detail.export_text": "匯出文字", + "detail.copy": "複製", + "detail.technical": "技術細節", + "companion.spliced_pill": "已配對伴生檔案", + "tab.overview": "概覽", + "tab.log": "記錄", + "tab.entries": "條目", + "batch.summary": "摘要", + "batch.inputs": "輸入項", + "batch.scan": "資料夾掃描", + "batch.non_target": "已略過的非目標", + "batch.walk_errors": "無法讀取的資料夾項目", + "batch.probe_errors": "探測錯誤", + "batch.scan_note": "資料夾掃描會檢查 .exe、.dll、.so、global-metadata.dat 和 Android 應用程式套件。", + "batch.scan_incomplete": "分析不完整:部分資料夾項目或所選檔案無法檢驗。", + "pkg.title": "應用程式套件", + "pkg.kind": "應用程式套件類型", + "pkg.package": "套件名稱", + "pkg.version": "版本", + "pkg.entries": "頂層條目", + "pkg.candidates": "待探測條目", + "pkg.nested": "巢狀應用程式套件", + "pkg.note": "僅會解壓縮並探測 .so 與 global-metadata.dat 條目。", + "pkg.result": "結果", + "pkg.manifests": "資訊清單", + "pkg.unnamed": "未命名", + "pkg.targets": "受保護條目與中繼資料", + "pkg.no_targets": "此應用程式套件中沒有受保護的條目,無須處理。", + "entries.title": "條目", + "entries.remapped_label": "已重新映射的方法欄位", + "col.name": "名稱", + "col.type": "類型", + "col.outcome": "結果", + "col.route": "方案", + "col.time": "時間", + "col.source": "來源", + "col.status": "狀態", + "common.yes": "是", + "common.no": "否", + "ov.messages": "訊息", + "ov.recognition": "識別", + "ov.platform": "平台", + "ov.format": "格式", + "ov.kind": "種類", + "ov.metadata": "il2cpp 中繼資料", + "ov.metadata_version": "中繼資料版本", + "ov.metadata_layout": "結構配置定義", + "ov.cap_seeded": "基於種子的方法權杖", + "ov.cap_structural": "結構化方法權杖", + "ov.cap_indices": "方法索引恢復", + "ov.cap_context": "需要應用程式上下文", + "ov.evidence": "依據", + "ov.no_evidence": "無保護依據", + "ov.routes": "復原方案", + "ov.selected": "已選用", + "ov.no_routes": "未嘗試任何復原方案。", + "ov.stages": "階段", + "ov.validation": "靜態驗證", + "ov.validation_metadata": "這裡的靜態驗證針對 PE 和 ELF;中繼資料的資料表結構會在轉換過程中驗證。", + "ov.validation_warnings": "復原後的映像有結構問題,可能無法執行。結果會標記為「可疑」,解包時仍會儲存檔案。", + "ov.validation_failed": "靜態驗證發現復原後的映像有致命的結構錯誤,很可能無法執行。結果會標記為「可疑」,解包時仍會儲存檔案。", + "ov.identity": "檔案識別資訊", + "ov.source": "輸入項", + "ov.companion": "伴生檔案", + "ov.recovered": "恢復映像", + "ov.output": "輸出", + "ov.restored_elf": "已恢復的 ELF", + "ov.elf_sections": "節區 · 區段", + "ov.elf_symbols": "動態符號", + "ov.elf_relocs": "重定位 · PLT", + "log.f_all": "全部", + "log.f_nosteps": "隱藏步驟", + "log.f_problems": "僅顯示問題", + "log.copy": "複製記錄", + "log.lv_info": "INFO", + "log.lv_step": "STEP", + "log.lv_warn": "WARN", + "log.lv_error": "ERROR", + "status.ready": "就緒", + "legal.title": "法律聲明:使用前請詳閱", + "legal.p1": "Senbei 是研究與互通性工具,用於對您已合法持有的軟體進行合法逆向工程、安全研究與保存。請僅處理您擁有或已獲明確授權分析的二進位檔。", + "legal.p2": "規避科技保護措施在您所在的司法管轄區可能受到限制(例如美國 DMCA §1201,其中包含針對安全研究與互通性的豁免條款)。確保您的使用行為合法是您本人的責任。", + "legal.p3": "Senbei 在您的電腦上對檔案執行純靜態轉換:它本身不繞過任何存取控制、從輸入檔案推導所需資訊、不包含任何廠商程式碼,且絕不執行或上傳其輸入項。某一種 Android 封裝變體的內嵌中繼資料層,是使用在分析單一組建時所恢復的 XOR 金鑰流進行解封;該金鑰流為隨附於工具中的研究產出,而非由廠商散佈的金鑰。", + "legal.p4": "Senbei 不提供連線遊玩、授權詐欺或作弊功能。請勿重新散佈已解密的輸出或將其上傳至任何地方。本軟體係依「現狀」提供,不附帶任何形式的擔保;作者對任何濫用行為概不負責。「CrackProof」為其所有權人的商標;本專案與該廠商或任何發行商均無關聯,亦未獲其背書。", + "legal.accept": "我已瞭解並同意", + "settings.title": "設定", + "settings.tab_general": "一般", + "settings.tab_memory": "記憶體", + "settings.tab_about": "關於", + "settings.language": "語言", + "settings.output": "預設輸出資料夾", + "settings.output_recent": "上次使用的資料夾", + "settings.output_choose": "選擇資料夾…", + "settings.reset": "重設為預設值", + "settings.done": "完成", + "about.desc": "適用於受 CrackProof 保護之 Windows PE 檔案與 Android AArch64 共用程式庫的靜態解包工具。", + "about.license": "授權條款", + "about.source": "原始碼", + "about.legal": "顯示法律聲明", + "status.ok": "已恢復", + "status.suspect": "可疑", + "status.skipped": "已略過", + "status.error": "錯誤", + "status.incomplete": "分析不完整", + "entryStatus.restored": "已恢復", + "entryStatus.not_target": "非目標", + "entryStatus.unchanged": "未變更", + "entryStatus.error": "錯誤", + "entryKind.shared_library": "共用程式庫", + "entryKind.metadata": "il2cpp 中繼資料", + "recognition.not_attempted": "未嘗試", + "recognition.recognized": "已識別", + "recognition.not_recognized": "未識別", + "recognition.blocked": "受阻", + "outcome.succeeded": "成功", + "outcome.rejected": "已拒絕", + "outcome.failed": "失敗", + "outcome.not_attempted": "未嘗試", + "validation.clean": "通過", + "validation.warnings": "警告", + "validation.failed": "失敗", + "validation.not_run": "未執行", + "stage.detection": "偵測", + "stage.recovery": "恢復", + "stage.static_validation": "靜態驗證", + "stage.output_write": "輸出寫入", + "stageStatus.ok": "正常", + "stageStatus.skipped": "已略過", + "stageStatus.failed": "失敗", + "stageStatus.blocked": "受阻", + "evidence.header_magic": "標頭魔術數字", + "evidence.companion_spliced": "伴生檔案已拼接", + "evidence.external_companion_declaration": "宣告外部伴生檔案", + "evidence.private_section": "私有節區", + "evidence.aes_schedule": "AES 金鑰排程", + "evidence.validated_metadata_transform": "已驗證的中繼資料轉換", + "platform.windows_pe": "Windows PE", + "platform.android_elf": "Android ELF", + "platform.il2cpp_metadata": "il2cpp 中繼資料", + "kind.native_exe": "原生可執行檔", + "kind.managed_exe": ".NET 可執行檔", + "kind.native_dll": "原生 DLL", + "kind.managed_dll": ".NET 組件 (DLL)", + "kindShort.native_exe": "EXE", + "kindShort.managed_exe": ".NET EXE", + "kindShort.native_dll": "DLL", + "kindShort.managed_dll": ".NET DLL", + "layout.exe_style": "EXE 風格載入器", + "layout.dll": "DLL 載入器", + "layout.android_staged": "Android 分階段載入器", + "layout.metadata_seeded": "基於種子的中繼資料轉換", + "layout.metadata_structural": "結構化中繼資料轉換", + "layout.metadata_method_indices": "中繼資料方法索引恢復", + "metaLayout.known": "已知", + "metaLayout.context_required": "需要應用程式上下文", + "metaLayout.unverified": "未驗證", + "companion.absent": "無", + "companion.spliced": "已拼接", + "companion.paired": "已配對", + "companion.unmatched": "不相符", + "companion.unreadable": "無法讀取", + "TbUnpackN": "解包 ({n})", + "GroupScanning": "掃描中… 目前候選:{n}", + "ScanStatus": "正在掃描 {p}… 目前候選:{n}", + "RunStep": "步驟 {i}/{n} · {s}", + "DetailLastRun": "{mode} · {t}", + "PkgInventory": "候選條目:{n}", + "EntriesOthers": "其他條目(非目標):{n}", + "EntriesSummary": "目標:{n}", + "EntriesShowNonTargets": "顯示非目標 ({n})", + "EntriesRemapped": "已重新映射的方法欄位:{n}", + "LogRunStarted": "{mode}已開始 · 輸入項:{n}", + "LogScan": "掃描完成:候選 {n},已略過非目標 {s}", + "LogInputStarted": "輸入項 {i}/{n}:{p}", + "LogCompanion": "已配對伴生檔案:{p}", + "LogStep": "步驟 {i}/{n}:{s}", + "LogEntry": "條目 {p}:{o}", + "LogInputFinished": "完成:{o} ({t})", + "LogSummary": "已恢復 {ok} · 可疑 {suspect} · 失敗 {failed} · 已略過 {skipped}", + "AboutVersion": "版本 {v}", + "TagMetadata": "il2cpp 中繼資料 v{v}", + "web.unpack_tip": "恢復所選輸入項。結果會保留在此分頁中,可隨時下載。", + "web.unpack_desc": "進行恢復。結果會保留在此分頁中,可隨時下載。", + "web.download": "下載", + "web.download_all": "全部下載 (.zip)", + "web.out_downloads": "瀏覽器下載", + "web.out_tip": "解包後檔案的儲存位置。", + "web.out_folder_help": "Senbei 會將檔案儲存到所選資料夾下的 unpack/。如果瀏覽器不允許直接儲存某些檔案(例如 .dll),這些檔案會打包成 senbei-remaining.*.zip。請將 ZIP 解壓縮到 unpack/。", + "web.out_unsupported": "此瀏覽器無法寫入資料夾,復原後的檔案只能透過下載儲存。", + "web.limit": "輸入大小上限", + "web.limit_help": "超過上限的輸入項不會被讀取。恢復過程中,輸入項與復原後的映像會同時保留在記憶體中。", + "web.over_limit": "此輸入項為 {size},超過 {limit} 的輸入大小上限。請在「設定」中調高上限,然後重新執行。", + "web.engine_stopped": "恢復引擎在完成前意外停止。此輸入項所需的記憶體可能超出此瀏覽器的上限。", + "web.embedded_metadata": "內嵌中繼資料", + "web.saved": "已儲存至 {path}", + "web.save_failed": "無法儲存 {path}。", + "web.save_refused": "此瀏覽器不允許將 {name} 儲存至資料夾。檔案已保留在此分頁中,可隨時下載。", + "web.read_failed": "無法讀取此輸入項。", +}; diff --git a/web/index.html b/web/index.html index be537f4..430d36b 100644 --- a/web/index.html +++ b/web/index.html @@ -3,86 +3,44 @@ -Senbei — static CrackProof unpacker + + + +Senbei + + + + + + + + + + + + - - -
    -
    -

    Senbei web

    - - - +
    +
    +
    Senbei
    -

    - Static unpacker for CrackProof-protected PE files, running entirely in - your browser. No file ever leaves your device. -

    - -
    -

    Drop files here or click to browse

    -

    - Protected .exe / .dll modules, optional - ._ companions, or an il2cpp - global-metadata.dat. Android packages - (.apk / .apks / .xapk) and - .so libraries are recognized but need the CLI. -

    - +
    + +
    - -
    - - -

    -
    - -
      - - - -
      -

      Legal notice · - Senbei is free software under the AGPL-3.0 license.

      +
      +
      +
      -
      - + + + + + + + + diff --git a/web/model.js b/web/model.js new file mode 100644 index 0000000..31c0d97 --- /dev/null +++ b/web/model.js @@ -0,0 +1,311 @@ +// Rules the page shares with the native front ends: which names a folder scan +// opens, how outputs are named, and which loose Android files belong to one +// application. No DOM and no I/O, so `web/tests/` runs these under Node. + +/** Smallest file a folder scan opens. A protected module needs this many bytes. */ +export const MIN_SIZE = 4128; + +/** Bytes read from the start of a file to classify it. */ +export const PREFIX_SIZE = 8192; + +export const METADATA_NAME = 'global-metadata.dat'; + +const MIB = 1024 * 1024; + +/** + * The input limit: default, and the range the setting accepts, in MiB. The + * engine itself refuses an input or an output over 1 GiB. + */ +export const DEFAULT_LIMIT_MIB = 512; +export const MIN_LIMIT_MIB = 8; +export const MAX_LIMIT_MIB = 1024; + +/** Bytes for a limit typed in MiB, or `fallback` when it is not in range. */ +export function parseLimitMiB(raw, fallback = DEFAULT_LIMIT_MIB * MIB) { + const text = String(raw ?? '').trim(); + if (text === '') return fallback; + const mib = Number(text); + if (!Number.isFinite(mib) || mib < MIN_LIMIT_MIB || mib > MAX_LIMIT_MIB) return fallback; + return Math.round(mib) * MIB; +} + +export function baseName(path) { + const slash = path.lastIndexOf('/'); + return slash < 0 ? path : path.slice(slash + 1); +} + +export function dirName(path) { + const slash = path.lastIndexOf('/'); + return slash < 0 ? '' : path.slice(0, slash); +} + +/** Reserve an archive path, disambiguating names on case-insensitive disks. */ +export function uniquePath(path, taken) { + let unique = path; + const dot = path.lastIndexOf('.'); + const slash = path.lastIndexOf('/'); + for (let n = 2; taken.has(unique.toLowerCase()); n += 1) { + unique = dot > slash ? `${path.slice(0, dot)} (${n})${path.slice(dot)}` : `${path} (${n})`; + } + taken.add(unique.toLowerCase()); + return unique; +} + +/** + * Order two paths as the native scan lists them: component by component, so a + * folder's files stay together, and by code unit within a component. + */ +export function comparePaths(a, b) { + const left = a.split('/'); + const right = b.split('/'); + for (let index = 0; index < left.length && index < right.length; index += 1) { + if (left[index] !== right[index]) return left[index] < right[index] ? -1 : 1; + } + return left.length - right.length; +} + +function extension(name) { + const dot = name.lastIndexOf('.'); + return dot < 0 ? '' : name.slice(dot + 1).toLowerCase(); +} + +/** True for the external payload of a module: `.exe._` or `.dll._`. */ +export function isCompanionName(name) { + return name.endsWith('._') && ['exe', 'dll'].includes(extension(name.slice(0, -2))); +} + +/** + * What a folder scan takes a file name for: `pe`, `so`, `package`, + * `metadata`, or `null` for a name it never opens. + */ +export function candidateKind(name) { + const file = baseName(name); + if (file.toLowerCase() === METADATA_NAME) return 'metadata'; + switch (extension(file)) { + case 'exe': + case 'dll': + return 'pe'; + case 'so': + return 'so'; + case 'apk': + case 'apks': + case 'xapk': + return 'package'; + default: + return null; + } +} + +/** True for a directory a scan does not enter: a previous output tree. */ +export function isOutputDir(name) { + return name.toLowerCase() === 'unpack'; +} + +/** What the first bytes of a file say it is. */ +export function sniff(prefix) { + const at = (i) => prefix[i] ?? -1; + return { + zip: at(0) === 0x50 && at(1) === 0x4b && at(2) === 0x03 && at(3) === 0x04, + metadata: at(0) === 0xaf && at(1) === 0x1b && at(2) === 0xb1 && at(3) === 0xfa, + mz: at(0) === 0x4d && at(1) === 0x5a, + elf64Aarch64: + at(0) === 0x7f && at(1) === 0x45 && at(2) === 0x4c && at(3) === 0x46 && + at(4) === 2 && at(5) === 1 && at(18) === 0xb7 && at(19) === 0, + }; +} + +/** `app.exe` becomes `app.unpack.exe`; a name with no dot gets `.unpack` appended. */ +export function outName(path) { + const dir = dirName(path); + const file = baseName(path); + const dot = file.lastIndexOf('.'); + const renamed = dot < 0 ? `${file}.unpack` : `${file.slice(0, dot)}.unpack${file.slice(dot)}`; + return dir ? `${dir}/${renamed}` : renamed; +} + +/** Where a library's embedded metadata goes: beside the restored library. */ +export function embeddedMetadataPath(restoredPath) { + const dir = dirName(restoredPath); + const name = outName(METADATA_NAME); + return dir ? `${dir}/${name}` : name; +} + +/** + * The application a loose Android file belongs to, or `null` when its path + * does not say. + * + * `/lib//.so` and `/assets/**\/global-metadata.dat` + * share ``. Anything else is on its own: a metadata blob is never paired + * with a library from somewhere else in the scan. + */ +export function looseAppRoot(relPath, kind) { + const parts = relPath.split('/'); + if (kind === 'so') { + if (parts.length < 3 || parts[parts.length - 3].toLowerCase() !== 'lib') return null; + return parts.slice(0, -3).join('/'); + } + if (kind === 'metadata') { + const dirs = parts.slice(0, -1).map((part) => part.toLowerCase()); + const assets = dirs.lastIndexOf('assets'); + return assets < 0 ? null : parts.slice(0, assets).join('/'); + } + return null; +} + +/** + * True for a package entry name that would leave the package: absolute, with + * a drive, holding a NUL, or climbing above the package root with `..`. A + * package with such an entry is refused as a whole, as the native front ends + * refuse it. + */ +export function escapesRoot(name) { + if (typeof name !== 'string' || name.includes('\0')) return true; + const normal = name.replace(/\\/g, '/'); + if (normal.startsWith('/') || /^[A-Za-z]:/.test(normal)) return true; + let depth = 0; + for (const part of normal.split('/')) { + if (part === '' || part === '.') continue; + if (part === '..') { + if (depth === 0) return true; + depth -= 1; + } else { + depth += 1; + } + } + return false; +} + +/** + * A package entry name as a safe relative path, or `null` for one that must + * not be used: absolute, with a drive, or climbing out with `..`. + */ +export function safeEntryPath(name) { + if (typeof name !== 'string' || name === '' || name.includes('\0')) return null; + const normal = name.replace(/\\/g, '/'); + if (normal.startsWith('/') || /^[A-Za-z]:/.test(normal)) return null; + const parts = []; + for (const part of normal.split('/')) { + if (part === '' || part === '.') continue; + if (part === '..') return null; + parts.push(part); + } + return parts.length === 0 ? null : parts.join('/'); +} + +/** True for a package entry the page reads: a library or a metadata blob. */ +export function isPackageTarget(path) { + const kind = candidateKind(path); + return kind === 'so' || kind === 'metadata'; +} + +/** True for an app package nested one level inside a bundle. */ +export function isNestedPackage(path) { + return extension(baseName(path)) === 'apk'; +} + +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`; +} + +/** A duration as the workbench writes it: `15 ms` or `1.42 s`. */ +export function formatDuration(ms) { + if (!Number.isFinite(ms) || ms < 0) return ''; + const whole = Math.round(ms); + return whole >= 1000 ? `${(whole / 1000).toFixed(2)} s` : `${whole} ms`; +} + +/** `0:01.4`: minutes, seconds, and tenths, for a running clock. */ +export function formatClock(elapsedMs) { + const tenths = Math.floor(Math.max(0, elapsedMs) / 100); + const seconds = String(Math.floor(tenths / 10) % 60).padStart(2, '0'); + return `${Math.floor(tenths / 600)}:${seconds}.${tenths % 10}`; +} + +/** `12,345`: a count with thousands separators. */ +export function formatCount(value) { + return String(value ?? '').replace(/\B(?=(\d{3})+(?!\d))/g, ','); +} + +/** `head…tail` of a hash for display. */ +export function shortHash(sha256) { + const text = String(sha256 ?? ''); + return text.length <= 24 ? text : `${text.slice(0, 16)}…${text.slice(-8)}`; +} + +/** `13:46:42.936`: the local time of day of a log line. */ +export function localClock(epochMs) { + const date = new Date(epochMs); + const two = (value) => String(value).padStart(2, '0'); + return `${two(date.getHours())}:${two(date.getMinutes())}:${two(date.getSeconds())}.${String(date.getMilliseconds()).padStart(3, '0')}`; +} + +/** The catalog language for a list of browser language tags. */ +export function languageFor(tags) { + for (const tag of tags ?? []) { + const parts = String(tag).toLowerCase().replace(/_/g, '-').split('-'); + switch (parts[0]) { + case 'en': + return 'en'; + case 'ja': + return 'ja'; + case 'ko': + return 'ko'; + case 'zh': { + const rest = parts.slice(1); + if (rest.includes('hant')) return 'zh-TW'; + if (rest.includes('hans')) return 'zh-CN'; + return rest.some((part) => ['tw', 'hk', 'mo'].includes(part)) ? 'zh-TW' : 'zh-CN'; + } + default: + } + } + return 'en'; +} + +/** + * How an input is shown after a job, from the engine's report. + * + * `ok` and `suspect` both have output. `skipped` covers an input that needed + * nothing: not protected, an already canonical metadata blob, or a metadata + * version left untouched by design. + */ +export function stateOf(info) { + switch (info?.status) { + case 'recovered': { + const validation = info.profile?.static_validation; + return info.suspect || validation === 'warnings' || validation === 'failed' ? 'suspect' : 'ok'; + } + case 'unchanged': + case 'unsupported': + case 'not_protected': + return 'skipped'; + default: + return 'failed'; + } +} + +/** Modules `0x0C` collected for one application, kept apart by content. */ +export class ModuleContext { + #modules = []; + + add(bytes) { + if (!bytes?.length) return; + const same = (other) => + other.length === bytes.length && other.every((value, index) => value === bytes[index]); + if (!this.#modules.some(same)) this.#modules.push(bytes); + } + + /** The distinct modules seen. A metadata blob binds only when this is one. */ + get count() { + return this.#modules.length; + } + + /** The single module, or `null` when there is none or more than one. */ + get module() { + return this.#modules.length === 1 ? this.#modules[0] : null; + } +} diff --git a/web/output.js b/web/output.js new file mode 100644 index 0000000..4fc4a89 --- /dev/null +++ b/web/output.js @@ -0,0 +1,149 @@ +// Writes for one batch of outputs, all going to the same chosen folder. + +import { formatLog } from './detail.js'; +import { uniquePath } from './model.js'; +import { fileStamp } from './report.js'; +import { allOutputs, archivePath, notify } from './state.js'; +import { shownPath } from './ui.js'; + +const inputLog = (items) => formatLog(items.flatMap((item) => item.log ?? [])); +const logBlob = (text) => new Blob([text], { type: 'text/plain;charset=utf-8' }); +const folderStamp = (date) => `${fileStamp(date.toISOString())}-${String(date.getUTCMilliseconds()).padStart(3, '0')}`; + +/** Bundle the retained outputs and their complete input logs for download. */ +export async function downloadArchive(items, now = new Date()) { + const outputs = allOutputs(items); + if (!outputs.length) return null; + const stamp = fileStamp(now.toISOString()); + const logPath = `senbei-${stamp}.log`; + const log = logBlob(inputLog(items)); + const taken = new Set([logPath]); + const files = outputs.map(({ item, output }) => ({ + path: uniquePath(archivePath(item, output), taken), + blob: output.blob, + })); + files.push({ path: logPath, blob: log }); + const { buildZip } = await import('./zip.js'); + return { blob: await buildZip(files, now), name: `senbei-unpack.${stamp}.zip` }; +} + +/** Write to a chosen folder; return false if the browser refused the file name. */ +async function writeFile(root, path, blob) { + const parts = path.split('/'); + let directory = root; + for (const part of parts.slice(0, -1)) { + directory = await directory.getDirectoryHandle(part, { create: true }); + } + let file; + try { + file = await directory.getFileHandle(parts.at(-1), { create: true }); + } catch (error) { + // Chromium refuses some names, including .dll, here. Do not treat a + // failure to open the directory or write the bytes as a name refusal. + if (error instanceof TypeError) return false; + throw error; + } + const writable = await file.createWritable(); + try { + await writable.write(blob); + await writable.close(); + } catch (error) { + await writable.abort().catch(() => {}); + throw error; + } + return true; +} + +function saved(output, path) { + output.saved = path; + output.saveFailed = null; + output.refused = false; +} + +export class FolderWriter { + #root; + #refused = []; + + constructor(root) { + this.#root = root; + } + + async save(item, fresh = false) { + const outputs = item.result?.outputs ?? []; + if (!outputs.length) return; + const root = this.#root; + // A scan of the chosen folder itself keeps the paths inside that folder. + const handle = item.group.handle; + const own = handle ? await root.isSameEntry(handle).catch(() => false) : false; + for (const output of outputs) { + if (!fresh && output.saved) continue; + const name = own ? output.path : archivePath(item, output); + const path = `unpack/${name}`; + output.saved = null; + output.saveFailed = null; + output.refused = false; + try { + if (await writeFile(root, path, output.blob)) { + saved(output, path); + notify('web.saved', { path: shownPath(path) }); + } else { + output.refused = true; + this.#refused.push({ item, name, output }); + } + } catch { + output.saveFailed = path; + notify('web.save_failed', { path: shownPath(path) }, 'err'); + } + } + } + + /** Save the unfiltered input logs beside the outputs, even if recovery failed. */ + async saveLog(items, now = new Date()) { + const text = inputLog(items); + if (!text) return; + const path = `unpack/senbei-${folderStamp(now)}.log`; + try { + if (await writeFile(this.#root, path, logBlob(text))) return; + } catch { + // The log remains available in the tab. + } + notify('web.save_failed', { path: shownPath(path) }, 'err'); + } + + /** Store refused files in one archive, retaining paths relative to unpack/. */ + async finish(now = new Date()) { + const refused = this.#refused; + this.#refused = []; + if (!refused.length) return; + const path = `unpack/senbei-remaining.${folderStamp(now)}.zip`; + let written = false; + try { + const { buildZip } = await import('./zip.js'); + const taken = new Set(); + const files = refused.map(({ name, output }) => ({ path: uniquePath(name, taken), blob: output.blob })); + written = await writeFile(this.#root, path, await buildZip(files, now)); + } catch { + // Retain the original blobs: the browser can still download them. + } + const parents = new Set(); + const groups = new Set(); + for (const { item, output } of refused) { + if (written) saved(output, path); + else output.saveFailed = path; + const parent = item.parent ?? item; + parents.add(parent); + groups.add(parent.group); + } + const line = { + at: Date.now(), + level: written ? 'info' : 'error', + type: 'stage', + stage: 'output_write', + status: written ? 'ok' : 'failed', + detail: { text: shownPath(path), path: true }, + }; + for (const item of parents) item.log?.push(line); + for (const group of groups) group.lastRun?.log.push(line); + notify(written ? 'web.saved' : 'web.save_failed', { path: shownPath(path) }, written ? undefined : 'err'); + } +} diff --git a/web/package.js b/web/package.js new file mode 100644 index 0000000..2570757 --- /dev/null +++ b/web/package.js @@ -0,0 +1,99 @@ +// App packages: what is in one, and where its libraries and metadata are. +// +// A package is listed from its ZIP directory. The manifest is read first, to +// name the application its entries belong to, and only `.so` and +// `global-metadata.dat` entries are ever read after that. An `.apks` or +// `.xapk` bundle is descended one level, into the `.apk` files it holds. + +import { entryBlob, entrySource, openZip, readEntryPrefix } from './zip.js'; +import { baseName, escapesRoot, isNestedPackage, isPackageTarget, safeEntryPath } from './model.js'; + +/** The manifest's `` start tag is read from at most this much. */ +const MANIFEST_PROBE = 4 * 1024 * 1024; + +const isRootManifest = (path) => path.toLowerCase() === 'androidmanifest.xml'; + +/** A package holds an entry whose name would leave the package. */ +export class UnsafeEntry extends Error { + constructor() { + super('unsafe entry path in package'); + this.name = 'UnsafeEntry'; + } +} + +/** + * List one archive: its targets and the application its manifest names. + * + * `label` is the archive's path inside its bundle, or `''` for the package + * itself. `identify(bytes, truncated)` reads a manifest. Throws + * [`UnsafeEntry`] for an archive with an entry name that leaves it. + */ +async function listArchive(blob, label, identify, limits) { + const { entries } = await openZip(blob, limits); + const archive = { label, blob, entryCount: entries.length, identity: null, targets: [], nested: [] }; + let manifest = null; + const seen = new Set(); + for (const entry of entries) { + if (entry.directory) continue; + if (escapesRoot(entry.name)) throw new UnsafeEntry(); + const path = safeEntryPath(entry.name); + // A name that is not a clean path, or one seen before, is never read. + if (!path || seen.has(path)) continue; + seen.add(path); + if (isRootManifest(path)) manifest ??= entry; + else if (isPackageTarget(path)) archive.targets.push({ path, entry }); + else if (isNestedPackage(path)) archive.nested.push({ path, entry }); + } + if (manifest) { + try { + const source = await entrySource(blob, manifest); + const { bytes, truncated } = await readEntryPrefix(source, MANIFEST_PROBE); + archive.identity = await identify(bytes, truncated); + } catch { + // A manifest that cannot be read names nothing; the package is isolated. + } + } + return archive; +} + +/** + * Inventory a package file. + * + * Returns `{ kind, archives, problems }`. `archives[0]` is the package itself + * and the rest are the `.apk` files of a bundle. Each archive has `label`, + * `blob`, `entryCount`, `identity` (`[package, version]` or `null`), and + * `targets` (`{ path, entry }`). `problems` lists nested packages that could + * not be opened. Nothing but directories and manifests is read, except a + * nested package that is deflated inside its bundle, which is inflated within + * `limits.maxNestedBytes`. Throws [`UnsafeEntry`] when the package or a + * package in it holds an entry name that leaves it. + */ +export async function inventory(file, name, identify, limits = {}) { + const kind = baseName(name).split('.').pop().toLowerCase(); + const top = await listArchive(file, '', identify, limits); + const archives = [top]; + const problems = []; + if (kind !== 'apk') { + for (const nested of top.nested) { + try { + const source = await entrySource(file, nested.entry); + // A stored entry is a slice of the bundle; nothing is copied. + const blob = source.method === 0 + ? source.blob + : await entryBlob(source, limits.maxNestedBytes ?? Infinity); + archives.push(await listArchive(blob, nested.path, identify, limits)); + } catch (error) { + if (error instanceof UnsafeEntry) throw error; + problems.push({ path: nested.path, message: String(error?.message ?? error) }); + } + } + } + return { kind, archives, problems }; +} + +/** The format version of a metadata entry, read from its first eight bytes. */ +export async function entryMetadataVersion(source) { + const { bytes } = await readEntryPrefix(source, 8); + if (bytes.length < 8) return null; + return new DataView(bytes.buffer, bytes.byteOffset, 8).getUint32(4, true); +} diff --git a/web/report.js b/web/report.js index 79c4751..f5b32fe 100644 --- a/web/report.js +++ b/web/report.js @@ -1,397 +1,285 @@ -// 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 ------------------------------------------------- +// What the page says about a finished input: the messages it shows, its +// stages, its log, and the JSON report. Pure transforms over the page's item +// records, so `web/tests/` runs them under Node. // -// 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. +// An item record is `{ name, relPath, kind, state, size, pre, result, error, +// container, entries }`. `result` is `{ info, lang, durationMs, retried, +// companionUsed, inputSha256, outputs }`, where `info` is the engine's report +// for the job and each output is `{ path, size, sha256, embedded, saved, +// saveFailed }`. +// +// A log line is `{ at, level, type, ... }`: `at` in milliseconds since the +// epoch, `level` one of `info`, `step`, `detail`, `warn`, `error`, and the +// rest by `type`. Lines stay structured so the log reads in whatever language +// the page is in when it is shown. -const FORMAT_LABEL = { - pe32: 'PE32', - pe32_plus: 'PE32+', - elf64_aarch64: 'ELF64 AArch64', - il2cpp_metadata: 'il2cpp metadata', -}; +import { baseName } from './model.js'; -const KIND_LABEL = { - native_exe: 'native EXE', - managed_exe: 'managed EXE', - native_dll: 'native DLL', - managed_dll: 'managed DLL', -}; +export const REPORT_SCHEMA = 'senbei.browser-report'; +export const REPORT_SCHEMA_VERSION = 2; -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 messageText = (message) => message?.text ?? ''; -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, ' '); +/** + * Every message an input reports, each exactly once, where a reader looks. + * + * Returns `{ top, validation }`, both lists of `{ tone, message }` with `tone` + * one of `err`, `warn`, `info`. When the static check found something, the + * profile's messages are its findings and go to `validation`; everything else + * goes to `top`. A message is `{ text, local }`. Why an input needed nothing + * is not a message: its recovery stage says so. + */ +export function messagePlan(item) { + const info = item?.result?.info; + const validation = []; + const top = []; + const shown = new Set(); + const push = (list, tone, message) => { + const text = messageText(message); + if (!text || shown.has(text)) return; + shown.add(text); + list.push({ tone, message }); + }; + if (item?.error) push(top, 'err', item.error); + if (!info) return { top, validation }; + const verdict = info.profile?.static_validation; + const findings = verdict === 'warnings' || verdict === 'failed'; + if (info.error) push(top, 'err', info.error); + for (const finding of info.findings ?? []) { + push(findings ? validation : top, finding.severity === 'fatal' ? 'err' : 'warn', { + text: finding.message, + local: null, + }); + } + for (const message of info.errors ?? []) push(findings ? validation : top, 'err', message); + for (const message of info.warnings ?? []) push(findings ? validation : top, 'warn', message); + return { top, validation }; } /** - * 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. + * True when an input's last run went through the Windows pipeline. That is + * every module, and every file that is no target at all: the pipeline is what + * tells such a file so. */ -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; -} +export const ranAsModule = (item) => + item?.result?.op ? item.result.op === 'pe' : !['so', 'metadata', 'package'].includes(item?.kind); /** - * Route/validation lines for a finished (or failed) recovery. + * The stages of a finished input, as the workbench records them: + * `{ stage, status, durationMs, detail }` with `stage` one of `detection`, + * `recovery`, `static_validation`, `output_write` and `status` one of `ok`, + * `skipped`, `failed`. `detail` is a message or `null`. * - * 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. + * A Windows module records all of its stages; a library and a metadata blob + * record recovery and what followed it. A failure records the one stage that + * failed. An output that was kept for download was not written anywhere, so + * its `output_write` is `skipped`. */ -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}`); +export function stagesOf(item) { + const result = item?.result; + const info = result?.info; + const stage = (name, status, extra) => ({ stage: name, status, durationMs: null, detail: null, ...extra }); + if (!info) return item?.error ? [stage('recovery', 'failed', { detail: item.error })] : []; + if (item.kind === 'package') return []; + const windows = ranAsModule(item); + const spent = Math.round(result.durationMs ?? 0); + switch (info.status) { + case 'recovered': { + const stages = windows ? [stage('detection', 'ok')] : []; + stages.push(stage('recovery', 'ok', { durationMs: spent })); + if (item.kind !== 'metadata') { + stages.push(stage('static_validation', windows && info.suspect ? 'failed' : 'ok')); + } + const outputs = result.outputs ?? []; + const saved = outputs.find((output) => output.saved); + if (outputs.some((output) => output.saveFailed)) stages.push(stage('output_write', 'failed')); + else if (saved) stages.push(stage('output_write', 'ok', { detail: { text: saved.saved, path: true } })); + // A refused name is queued for the folder ZIP; that write logs its + // outcome separately once the archive is complete. + else if (outputs.some((output) => !output.refused)) stages.push(stage('output_write', 'skipped')); + return stages; } + case 'unchanged': + // A file run on its own records how long the look took; one of a folder + // records why it needed nothing. + return [ + stage('recovery', 'skipped', item.group?.kind === 'folder' ? { detail: info.note ?? null } : { durationMs: spent }), + ]; + case 'unsupported': + case 'not_protected': + return [stage('recovery', 'skipped', { detail: info.note ?? null })]; + default: + return [stage('recovery', 'failed', { detail: windows ? (info.error ?? null) : null })]; } - // 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); +} + +const LEVEL_OF = { err: 'error', warn: 'warn' }; + +/** + * The engine's own lines of one job: its steps and their details. + * + * `began` is when the job started, as milliseconds since the epoch; every + * line's `at` is counted from it. `lang` is the language the job ran in, which + * a step title without a catalog name is written in. + */ +export function engineLines(info, began, lang) { + const lines = []; + let last = 0; + for (const line of info?.log ?? []) { + last = line.ms ?? last; + const at = began + last; + if (line.step !== undefined) { + lines.push({ + at, + level: 'step', + type: 'step', + i: line.i ?? null, + of: line.of ?? null, + key: line.key ?? null, + title: line.step, + lang, + }); + } else if (line.detail !== undefined) { + lines.push({ at, level: 'detail', type: 'detail', text: line.detail }); + } else if (line.truncated) { + lines.push({ at, level: 'detail', type: 'detail', text: '…' }); + } } 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}`, - ); +/** + * The lines that close an input's log at `at`: its stages, its messages, the + * entries of a package, and the outcome. + * + * `outcome` is `{ key, tone }` for the input, and `entries` lists the package + * entries a run acted on as `{ path, key, tone }`. + */ +export function closingLines(item, at, outcome, entries = []) { + const lang = item.result?.lang; + const lines = []; + for (const stage of stagesOf(item)) { + lines.push({ at, level: stage.status === 'failed' ? 'error' : 'info', type: 'stage', lang, ...stage }); + } + const plan = messagePlan(item); + for (const { tone, message } of [...plan.top, ...plan.validation]) { + lines.push({ at, level: LEVEL_OF[tone] ?? 'info', type: 'message', message, lang }); + } + for (const entry of entries) { + lines.push({ + at, + level: entry.tone === 'err' ? 'error' : 'info', + type: 'entry', + path: entry.path, + outcome: entry.key, + }); + } + lines.push(finishedLine(item, at, outcome)); + return lines; +} + +/** The line that says how an input ended and how long it took. */ +export function finishedLine(item, at, outcome) { + return { + at, + level: LEVEL_OF[outcome.tone] ?? 'info', + type: 'finished', + outcome: outcome.key, + durationMs: item.durationMs ?? item.result?.durationMs ?? 0, + }; +} + +/** The line that names the companion a module was paired with. */ +export function companionLine(item, at) { + return { at, level: 'info', type: 'companion', name: `${baseName(item.relPath)}._` }; +} + +/** One input's entry in the JSON report. */ +export function fileReport(item) { + const result = item.result ?? null; + const info = result?.info ?? null; + // A package has no job of its own; its time is that of its entries. + const duration = item.durationMs ?? result?.durationMs; + const report = { + name: item.name, + path: item.relPath, + kind: item.kind, + status: item.state, + input: { size: item.size ?? null, sha256: result?.inputSha256 ?? null }, + companion_used: result?.companionUsed === true, + forced_exe_retry: result?.retried === true, + duration_ms: Number.isFinite(duration) ? Math.round(duration) : null, + outputs: (result?.outputs ?? []).map((output) => ({ + path: output.path, + size: output.size, + sha256: output.sha256 ?? null, + embedded_metadata: output.embedded === true, + })), + // The engine's profile, verbatim. Before a run it is the pre-recovery one. + profile: info?.profile ?? item.pre ?? null, + findings: info?.findings ?? [], + metadata: info?.metadata ?? null, + restored_elf: info?.elf ?? null, + error: messageText(item.error) || messageText(item.identityError) || messageText(info?.error) || null, + }; + if (item.container) { + report.container = { + kind: item.container.kind, + archives: item.container.archives.map((archive) => ({ + path: archive.label || null, + entries: archive.entryCount, + candidates: archive.targets.length, + package: archive.identity?.[0] ?? null, + version: archive.identity?.[1] ?? null, + })), + }; + report.entries = (item.entries ?? []).map(fileReport); + } + return report; +} + +/** The report for `items`. `generatedAt` is passed in so this stays pure. */ +export function buildReport(items, options = {}) { + const files = items.map(fileReport); + const count = (state) => files.filter((file) => file.status === state).length; + return { + schema: REPORT_SCHEMA, + schema_version: REPORT_SCHEMA_VERSION, + tool: { name: 'senbei-web', version: options.version ?? null }, + generated_at: options.generatedAt ?? null, + input_limit_bytes: Number.isFinite(options.limitBytes) ? options.limitBytes : null, + summary: { + inputs: files.length, + recovered: count('ok'), + suspect: count('suspect'), + failed: count('failed'), + skipped: count('skipped'), + }, + files, + }; +} + +/** Two-space JSON with a trailing newline. */ +export function serializeReport(report) { + return `${JSON.stringify(report, null, 2)}\n`; +} + +/** `YYYYMMDD-HHMMSS` from an ISO timestamp, for file names. */ +export function fileStamp(generatedAt) { + return String(generatedAt ?? '') + .replace(/\D/g, '') + .slice(0, 14) + .replace(/^(\d{8})(\d{6})$/, '$1-$2'); +} + +/** + * A report's file name: safe on every filesystem, stable across time zones. + * `extension` is `json` for the report and `txt` for its text form. + */ +export function reportFileName(name, generatedAt, extension = 'json') { + const stamp = fileStamp(generatedAt); + const stem = name + ? baseName(name).replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^[_.]+|[_.]+$/g, '') || 'senbei' + : 'senbei'; + return stamp ? `${stem}.${stamp}.report.${extension}` : `${stem}.report.${extension}`; } diff --git a/web/run.js b/web/run.js new file mode 100644 index 0000000..26c64fb --- /dev/null +++ b/web/run.js @@ -0,0 +1,494 @@ +// Running recoveries: the order they run in, one job for each input or +// package entry, the logs they leave, and writing outputs to a chosen folder. + +import { language, t } from './i18n.js'; +import { + archiveAppKey, + changed, + fullPath, + isDone, + outcomeOf, + state, + targetEntries, + timeOf, +} from './state.js'; +import { + MIN_SIZE, + ModuleContext, + embeddedMetadataPath, + formatBytes, + looseAppRoot, + outName, + sniff, + stateOf, +} from './model.js'; +import { EngineStopped, Prober, runJob } from './engine.js'; +import { FolderWriter } from './output.js'; +import { closingLines, companionLine, engineLines, finishedLine } from './report.js'; +import { shownPath } from './ui.js'; + +/** A message the page raised: its catalog key, and what the system said. */ +export function pageError(key, vars, tech) { + return { key, vars, text: t(key, vars), tech: tech ? String(tech) : undefined }; +} + +// ---------- one job ---------- + +/** A library entry this small is probed in the shared worker before a job. */ +const QUICK_PROBE_BYTES = 32 * 1024 * 1024; + +function appKeyOf(target) { + if (target.isEntry) return archiveAppKey(target.parent, target.archive); + // Picked files carry no path, so the ones added together are one application. + if (target.group.kind === 'files') return `files:${target.group.id}`; + const root = looseAppRoot(target.relPath, target.kind); + return root === null ? `alone:${target.id}` : `loose:${target.group.id}:${root}`; +} + +function contextOf(target) { + const key = appKeyOf(target); + let context = state.contexts.get(key); + if (!context) { + context = new ModuleContext(); + state.contexts.set(key, context); + } + return context; +} + +function outputPath(target) { + if (!target.isEntry) return outName(target.relPath); + const inside = outName(target.target.path); + const label = target.archive.label; + return `${target.parent.relPath}/${label ? `${label}/` : ''}${inside}`; +} + +/** The outcome of a target that needs no job: the engine has nothing to restore. */ +function notTarget(profile = null) { + return { + op: null, + info: { + status: 'not_protected', + kind: null, + error: null, + note: null, + profile, + routes: [], + warnings: [], + errors: [], + findings: [], + suspect: false, + companion: false, + metadata: null, + elf: null, + log: [], + }, + image: null, + embedded: null, + moduleBytes: null, + identity: null, + }; +} + +/** An error that carries the message the page shows for it. */ +function failure(page) { + const error = new Error(page.text); + error.page = page; + return error; +} + +const overLimit = (size) => + failure(pageError('web.over_limit', { size: formatBytes(size), limit: formatBytes(state.limitBytes) })); + +/** + * Recover one input or package entry. + * + * Resolves to `{ outcome, companion, retried }`: the job's outcome, the + * companion file that was passed, and whether the other route was tried. `on` + * is given to the job, with `on.retry` called before a second attempt; + * `prober` answers the quick checks on package entries. + */ +async function attempt(target, lang, on, prober) { + if (target.kind === 'package') { + // A package that could not be listed fails as it failed then. One that + // holds nothing to probe needs nothing. + if (target.identityError) throw failure(target.identityError); + return { outcome: notTarget() }; + } + if (target.size > state.limitBytes) throw overLimit(target.size); + let input; + let version = target.metadataVersion; + if (target.isEntry) { + const { entrySource, readEntryPrefix } = await import('./zip.js'); + input = await entrySource(target.archive.blob, target.target.entry); + const magic = sniff((await readEntryPrefix(input, 20)).bytes); + if (target.kind === 'so') { + if (target.size < MIN_SIZE || !magic.elf64Aarch64) return { outcome: notTarget() }; + if (target.size <= QUICK_PROBE_BYTES) { + const profile = await prober.library(input, target.size); + if (profile?.recognition === 'not_recognized') return { outcome: notTarget(profile) }; + } + } else { + if (!magic.metadata) return { outcome: notTarget() }; + version = await (await import('./package.js')).entryMetadataVersion(input); + target.metadataVersion = version; + } + } else { + input = await target.open(); + } + + if (target.kind === 'so') { + if (target.isEntry) return { outcome: await runJob({ op: 'so', input, lang }, on) }; + // A file that turns out to be an ordinary library is told so the way any + // other file is, below. Its outcome is not shown before that. + const protectedOnly = (outcome) => outcome.info.status !== 'not_protected' && on.result?.(outcome); + const outcome = await runJob({ op: 'so', input, lang }, { ...on, result: protectedOnly }); + if (outcome.info.status !== 'not_protected') return { outcome }; + on.retry?.(); + } + + if (target.kind === 'metadata') { + // Only a v24 blob is bound to module 0x0C of its application. + const context = version === 24 ? state.contexts.get(appKeyOf(target)) : null; + const request = { + op: 'metadata', + input, + moduleBytes: context?.module ?? null, + conflicting: context?.count ?? 0, + lang, + }; + return { outcome: await runJob(request, on) }; + } + + // Anything else is tried as a Windows module, which is also how a file that + // is no target at all is told so. + const openCompanion = target.group.companions.get(`${target.relPath}._`); + const companion = openCompanion ? await openCompanion() : null; + if (companion && companion.size > state.limitBytes) throw overLimit(companion.size); + const request = { op: 'pe', input, companion, forceExe: false, lang }; + try { + return { outcome: await runJob(request, on), companion }; + } catch (error) { + const dll = (target.peKind ?? '').endsWith('dll'); + if (!(error instanceof EngineStopped && error.trap && dll)) throw error; + // The DLL route trapped. The EXE-only route is the other one to try. + on.retry?.(); + return { outcome: await runJob({ ...request, forceExe: true }, on), companion, retried: true }; + } +} + +// ---------- outputs ---------- + +function writerForOutput() { + return state.out.mode === 'folder' && state.out.dir ? new FolderWriter(state.out.dir) : null; +} + +/** Write what's already in the tab; a new folder gets even previously saved outputs. */ +export async function saveAll(items, fresh) { + const writer = writerForOutput(); + if (!writer || state.run || state.saving) return; + state.saving = true; + changed(); + try { + for (const item of items) { + await writer.save(item, fresh); + for (const entry of item.entries ?? []) await writer.save(entry, fresh); + } + await writer.finish(); + await writer.saveLog(items); + } finally { + state.saving = false; + changed(); + } +} + +// ---------- a run ---------- + +/** The jobs of an input: itself, or each entry of a package. */ +const leavesOf = (item) => (item.kind === 'package' && item.entries.length ? item.entries : [item]); + +/** + * The order the jobs of `items` run in. + * + * Inputs run in list order, each with its jobs together. A metadata blob is + * the exception: it may need module `0x0C` of its application, so it waits + * until every library of that application in this run has been restored. + */ +function schedule(items) { + const libraries = new Map(); + const count = (leaf, by) => { + const key = appKeyOf(leaf); + libraries.set(key, (libraries.get(key) ?? 0) + by); + }; + for (const item of items) for (const leaf of leavesOf(item)) if (leaf.kind === 'so') count(leaf, 1); + const now = []; + const later = []; + for (const item of items) { + const leaves = leavesOf(item); + for (const leaf of leaves) { + if (leaf.kind === 'metadata') continue; + now.push(leaf); + if (leaf.kind === 'so') count(leaf, -1); + } + for (const leaf of leaves) { + if (leaf.kind !== 'metadata') continue; + (libraries.get(appKeyOf(leaf)) > 0 ? later : now).push(leaf); + } + } + return [...now, ...later]; +} + +/** How a package reads once its entries ran: failed, restored, or left alone. */ +function packageState(item) { + const has = (...states) => item.entries.some((entry) => states.includes(entry.state)); + if (has('failed')) return 'failed'; + return has('ok', 'suspect') ? 'ok' : 'skipped'; +} + +function beginInput(run, input) { + const groupRun = run.groups.get(input.group); + const at = Date.now(); + groupRun.index += 1; + input.state = 'running'; + input.error = null; + input.durationMs = null; + input.clock = performance.now(); + const started = { + at, + level: 'info', + type: 'input-started', + i: groupRun.index, + n: groupRun.inputs, + path: shownPath(fullPath(input)), + }; + // An input's own log starts like the run it is part of. + input.log = [{ at, level: 'info', type: 'run-started', n: groupRun.inputs }, started]; + groupRun.log.push(started); + run.begun.add(input); +} + +function finishInput(run, input) { + const groupRun = run.groups.get(input.group); + const at = Date.now(); + let entries = []; + if (input.kind === 'package' && input.entries.length) { + input.durationMs = performance.now() - input.clock; + input.state = packageState(input); + entries = targetEntries(input).map((entry) => ({ + path: shownPath(entry.target.path), + ...outcomeOf(entry), + })); + } else if (input.result?.companionUsed) { + input.log.splice(2, 0, companionLine(input, input.log[1].at)); + } + // An input that ended without an outcome did not finish its work. + if (!isDone(input)) input.state = 'failed'; + const outcome = outcomeOf(input); + input.log.push(...closingLines(input, at, outcome, entries)); + groupRun.log.push(finishedLine(input, at, outcome)); + groupRun.durationMs += timeOf(input) ?? 0; + groupRun.finished.push(input); + run.done += 1; + if (run.current === input) { + run.current = null; + run.step = null; + } +} + +async function runLeaf(run, leaf, input, prober, writer) { + const lang = language(); + const clock = performance.now(); + const mark = input.log.length; + let heard = null; + if (run.current !== input) run.started = clock; + run.current = input; + run.step = null; + leaf.state = 'running'; + leaf.error = null; + leaf.result = null; + changed(); + + const settle = (outcome) => { + const { info } = outcome; + const outputs = []; + const path = outputPath(leaf); + const add = (blob, at, embedded) => + outputs.push({ path: at, blob, size: blob.size, sha256: null, embedded, saved: null, saveFailed: null, refused: false }); + if (outcome.image) add(outcome.image, path, false); + if (outcome.embedded) add(outcome.embedded, embeddedMetadataPath(path), true); + leaf.result = { + info, + lang, + // The job that gave the outcome: `pe`, `so`, `metadata`, or `null`. + op: outcome.op ?? null, + durationMs: performance.now() - clock, + retried: false, + companionUsed: info.companion === true, + companionSize: null, + companionSha256: null, + inputSha256: null, + outputs, + }; + leaf.state = stateOf(info); + // The engine's own lines, with their details, replace the ones heard + // while it ran. Its clock started when its first step did. + const lines = info.log ?? []; + const first = lines.find((line) => line.step !== undefined)?.ms ?? 0; + const last = lines.reduce((ms, line) => line.ms ?? ms, 0); + input.log.length = mark; + input.log.push(...engineLines(info, heard === null ? Date.now() - last : heard - first, lang)); + if (outcome.moduleBytes) contextOf(leaf).add(outcome.moduleBytes); + run.step = null; + changed(); + }; + const on = { + step: (step) => { + const at = Date.now(); + heard ??= at; + run.step = step; + input.log.push({ + at, + level: 'step', + type: 'step', + i: step.i ?? null, + of: step.of ?? null, + key: step.key ?? null, + title: step.title, + lang, + }); + changed(); + }, + retry: () => { + input.log.length = mark; + heard = null; + run.step = null; + }, + // The outcome is shown as soon as it is known; its digests follow. + result: settle, + }; + + try { + const done = await attempt(leaf, lang, on, prober); + if (!leaf.result) settle(done.outcome); + const result = leaf.result; + result.retried = done.retried === true; + result.companionSize = result.companionUsed ? (done.companion?.size ?? null) : null; + const identity = done.outcome.identity; + if (identity) { + result.inputSha256 = identity.input; + result.companionSha256 = identity.companion; + for (const output of result.outputs) { + output.sha256 = output.embedded ? identity.embedded : identity.image; + } + } + if (writer) await writer.save(leaf); + } catch (error) { + // Once the outcome is known, a later failure costs only the digests. + if (!leaf.result) { + leaf.state = 'failed'; + const memory = error instanceof EngineStopped || /not enough memory/i.test(error?.message ?? ''); + leaf.error = + error?.page ?? + pageError(memory ? 'web.engine_stopped' : 'web.read_failed', null, error?.message ?? error); + } + } + if (!leaf.isEntry) leaf.durationMs = leaf.result?.durationMs ?? performance.now() - clock; + run.step = null; + changed(); +} + +/** + * Run `items`, one job at a time. Every input is run again, whatever its last + * run found. Resolves when the run has ended. + */ +export async function startRun(items) { + if (state.run || state.saving || state.scans.length || items.length === 0) return; + const writer = writerForOutput(); + const plan = schedule(items); + const left = new Map(items.map((item) => [item, leavesOf(item).length])); + const run = { + total: items.length, + done: 0, + current: null, + step: null, + started: performance.now(), + stopping: false, + /** The input a stop lets finish. */ + keep: null, + begun: new Set(), + groups: new Map(), + }; + const at = Date.now(); + for (const item of items) { + // An earlier result stands until the input is reached. + item.prior = isDone(item) ? item.state : null; + item.state = 'queued'; + let groupRun = run.groups.get(item.group); + if (!groupRun) { + groupRun = { inputs: 0, index: 0, durationMs: 0, running: true, log: [], finished: [] }; + run.groups.set(item.group, groupRun); + item.group.lastRun = groupRun; + } + groupRun.inputs += 1; + } + for (const [group, groupRun] of run.groups) { + groupRun.log.push({ at, level: 'info', type: 'run-started', n: groupRun.inputs }); + // A run of a whole folder reports what the folder's scan found. + if (group.kind === 'folder' && groupRun.inputs === group.items.length) { + groupRun.log.push({ at, level: 'info', type: 'scan', n: group.items.length, s: group.stats.skipped }); + groupRun.scanned = true; + } + } + state.run = run; + state.notice = null; + changed(); + + const prober = new Prober(); + try { + for (const leaf of plan) { + const input = leaf.parent ?? leaf; + if (run.stopping && input !== run.keep) continue; + if (!run.begun.has(input)) beginInput(run, input); + await runLeaf(run, leaf, input, prober, writer); + left.set(input, left.get(input) - 1); + if (left.get(input) === 0) finishInput(run, input); + } + } finally { + prober.close(); + for (const item of items) { + if (item.state === 'queued') { + // The run never reached it: what it was before still stands. + item.state = item.prior ?? 'cancelled'; + } else if (item.state === 'running') { + // Stopped part way through a package: it ends with what ran. + finishInput(run, item); + } + delete item.prior; + delete item.clock; + } + if (writer) await writer.finish(); + const ended = Date.now(); + for (const [group, groupRun] of run.groups) { + const { stats } = group; + if (groupRun.scanned && stats.walkErrors + stats.probeErrors > 0) { + groupRun.log.push({ at: ended, level: 'warn', type: 'scan-incomplete' }); + } + const counts = { ok: 0, suspect: 0, failed: 0, skipped: 0 }; + for (const item of groupRun.finished) if (isDone(item)) counts[item.state] += 1; + groupRun.log.push({ at: ended, level: 'info', type: 'summary', counts }); + groupRun.running = false; + } + // Unstarted inputs can still have logs from an earlier run. + if (writer) await writer.saveLog([...run.begun]); + state.run = null; + changed(); + } +} + +/** Stop the run once the input in progress has finished. */ +export function cancelRun() { + const run = state.run; + if (!run || run.stopping) return; + run.stopping = true; + run.keep = run.current; + changed(); +} diff --git a/web/scan.js b/web/scan.js new file mode 100644 index 0000000..9ba6eb7 --- /dev/null +++ b/web/scan.js @@ -0,0 +1,89 @@ +// Folder walking for the two ways a browser hands over a whole folder: a +// dropped directory entry, and the file list of a folder input. +// +// A `FileSystemDirectoryHandle` is not walked. Chromium leaves some names out +// of a handle's listing and refuses to open them by name (`.dll` among them), +// so a scan through one would miss protected modules without a sign of it. +// +// A walk opens nothing. It yields a path and a way to get the `File`, and the +// scan asks for the file only when the name is one it probes, so bulk assets +// are never opened. + +import { candidateKind, comparePaths, isCompanionName, isOutputDir } from './model.js'; + +function readBatch(reader) { + return new Promise((resolve, reject) => reader.readEntries(resolve, reject)); +} + +/** + * Walk a dropped `FileSystemDirectoryEntry`. Yields `{ path, open }` for every + * file, with `path` relative to the entry. `onError` is called for each + * directory that could not be listed. + */ +export async function* walkEntry(directory, onError, prefix = '') { + const reader = directory.createReader(); + const folders = []; + try { + // `readEntries` returns the listing in batches and an empty one at the end. + for (;;) { + const batch = await readBatch(reader); + if (batch.length === 0) break; + for (const entry of batch) { + const path = prefix ? `${prefix}/${entry.name}` : entry.name; + if (entry.isDirectory) { + if (!isOutputDir(entry.name)) folders.push([path, entry]); + } else { + yield { path, open: () => new Promise((resolve, reject) => entry.file(resolve, reject)) }; + } + } + } + } catch (error) { + onError?.(error); + } + for (const [path, entry] of folders) yield* walkEntry(entry, onError, path); +} + +/** + * Walk the `FileList` of a folder input. Each file's `webkitRelativePath` + * starts with the picked folder's name, which is dropped. + */ +export function* walkFileList(files) { + for (const file of files) { + const parts = (file.webkitRelativePath || file.name).split('/'); + const inside = parts.slice(1); + if (inside.length === 0) continue; + if (inside.slice(0, -1).some(isOutputDir)) continue; + yield { path: inside.join('/'), open: async () => file }; + } +} + +/** The name of the folder a folder input picked. */ +export function fileListRoot(files) { + const first = files[0]; + return first ? (first.webkitRelativePath || first.name).split('/')[0] : ''; +} + +/** + * Sort a walk into what the scan probes. + * + * Returns `{ candidates, companions }`: the files whose names are targets, in + * path order whatever order the browser listed them in, and the companion + * payloads by path. Every other file is passed over without being opened. + * `signal` stops the walk. + */ +export async function collect(walk, signal) { + const candidates = []; + const companions = new Map(); + for await (const file of walk) { + if (signal?.aborted) break; + const name = file.path.slice(file.path.lastIndexOf('/') + 1); + if (isCompanionName(name)) { + companions.set(file.path, file.open); + continue; + } + const kind = candidateKind(name); + if (kind) candidates.push({ path: file.path, kind, open: file.open }); + } + candidates.sort((a, b) => comparePaths(a.path, b.path)); + return { candidates, companions }; +} diff --git a/web/state.js b/web/state.js new file mode 100644 index 0000000..446d793 --- /dev/null +++ b/web/state.js @@ -0,0 +1,251 @@ +// What the page holds, and the questions the views ask of it. + +import { DEFAULT_LIMIT_MIB, baseName, candidateKind, dirName } from './model.js'; + +export const VERSION = '1.4.0'; + +export const state = { + /** Added inputs: one group for loose files, one for each folder. */ + groups: [], + /** Id of the group, input, or package entry the detail pane shows. */ + selected: null, + /** Ids picked with Ctrl or Cmd; when not empty, a run takes these. */ + multi: [], + filter: 'all', + search: '', + tab: 'overview', + logLevel: 'all', + collapsed: new Set(), + /** Keys of the folded parts of the detail pane that were opened. */ + unfolded: new Set(), + /** The entries tab also lists entries that are not targets. */ + showNonTargets: false, + /** + * The run in progress: `{ total, done, current, step, started, stopping, + * keep, begun, groups }`. `current` is the input being processed and `step` + * the engine step it is at. + */ + run: null, + /** Folder and file scans in progress, each `{ group, controller }`. */ + scans: [], + /** Where outputs go: kept for download, or also written into `dir`. */ + out: { mode: 'downloads', dir: null }, + /** Outputs from an earlier run are being written to the chosen folder. */ + saving: false, + limitBytes: DEFAULT_LIMIT_MIB * 1024 * 1024, + settingsTab: 'general', + /** On a narrow window, whether the detail pane is the one shown. */ + showDetail: false, + /** Module `0x0C` images by application. */ + contexts: new Map(), + /** A line the status bar shows until the next action. */ + notice: null, +}; + +let nextId = 1; +export const newId = (prefix) => `${prefix}${nextId++}`; + +let listener = () => {}; + +/** Call `callback` whenever the state changed and the page must redraw. */ +export const onChange = (callback) => { + listener = callback; +}; + +/** Say that the state changed. */ +export const changed = () => listener(); + +/** Show a catalog message in the status bar, or clear it with no key. */ +export function notify(key, vars, tone) { + state.notice = key ? { key, vars, tone } : null; + changed(); +} + +// ---------- records ---------- + +/** A group of inputs: the loose files, or one folder. */ +export function makeGroup(kind, name, handle = null) { + return { + id: newId('g'), + kind, + name, + handle, + items: [], + scanning: false, + found: 0, + stats: { skipped: 0, walkErrors: 0, probeErrors: 0 }, + /** Companion payloads by path, each a function that opens the file. */ + companions: new Map(), + /** The last run over this group: `{ inputs, index, durationMs, running, log }`. */ + lastRun: null, + }; +} + +/** + * One input. `state` is `pending`, `queued`, `running`, `cancelled`, or one of + * the outcomes `ok`, `suspect`, `failed`, `skipped`. + */ +export function makeItem(group, candidate, size) { + return { + id: newId('i'), + group, + name: baseName(candidate.path), + relPath: candidate.path, + open: candidate.open, + size, + kind: 'other', + /** The pre-recovery profile, when a probe produced one. */ + pre: null, + peKind: null, + metadataVersion: null, + notProtected: false, + state: 'pending', + result: null, + error: null, + /** The log and the duration of the last run. */ + log: null, + durationMs: null, + container: null, + entries: null, + }; +} + +/** The entries of a package that a run probes. */ +export function makeEntries(item) { + return item.container.archives.flatMap((archive) => + archive.targets.map((target) => ({ + id: newId('e'), + isEntry: true, + parent: item, + group: item.group, + archive, + target, + name: baseName(target.path), + relPath: archive.label ? `${archive.label}/${target.path}` : target.path, + kind: candidateKind(target.path), + size: target.entry.size, + pre: null, + metadataVersion: null, + state: 'pending', + result: null, + error: null, + })), + ); +} + +// ---------- questions ---------- + +export const allItems = () => state.groups.flatMap((group) => group.items); + +/** The current batch owns its destination until its last write. */ +export const outputBusy = () => state.run !== null || state.saving; + +/** The group, input, or entry with `id`. */ +export function find(id) { + for (const group of state.groups) { + if (group.id === id) return { group }; + for (const item of group.items) { + if (item.id === id) return { item }; + const entry = item.entries?.find((candidate) => candidate.id === id); + if (entry) return { item: entry }; + } + } + return null; +} + +/** True once an input has the outcome of a run. */ +export const isDone = (item) => ['ok', 'suspect', 'failed', 'skipped'].includes(item.state); + +/** True while an input waits for a run that was started, or is in it. */ +export const isBusy = (item) => item.state === 'queued' || item.state === 'running'; + +/** True when anything is selected, so a run covers the selection. */ +export const hasSelection = () => state.multi.length > 0 || state.selected !== null; + +/** + * The inputs a run covers: the picked rows, else the selection, else every + * input. A group stands for all of its inputs and an entry for its package. + */ +export function targets() { + const picked = state.multi.length ? state.multi : state.selected ? [state.selected] : null; + if (!picked) return allItems(); + const chosen = new Set(); + for (const id of picked) { + const found = find(id); + if (found?.group) for (const item of found.group.items) chosen.add(item); + else if (found?.item) chosen.add(found.item.parent ?? found.item); + } + // Group order, whatever order the rows were picked in. + return allItems().filter((item) => chosen.has(item)); +} + +/** + * The path a row stands for: the folder's name, then the path inside it. An + * entry is its package, then its path inside the archive that holds it. + */ +export function fullPath(item) { + if (item.isEntry) return `${fullPath(item.parent)} › ${item.target.path}`; + return item.group?.kind === 'folder' ? `${item.group.name}/${item.relPath}` : item.relPath; +} + +/** How long the last run of an input took, in milliseconds. */ +export const timeOf = (item) => item.durationMs ?? item.result?.durationMs ?? null; + +const TONE = { ok: 'ok', suspect: 'warn', failed: 'err', skipped: 'skip' }; + +/** How a finished input reads: `{ tone, key }`, `key` being a catalog key. */ +export function outcomeOf(item) { + const tone = TONE[item.state] ?? 'skip'; + if (item.isEntry) { + const key = item.state === 'failed' + ? 'entryStatus.error' + : isNonTarget(item) + ? 'entryStatus.not_target' + : item.state === 'skipped' + ? 'entryStatus.unchanged' + : 'entryStatus.restored'; + // An entry reads as restored, failed, or left alone; it has no suspect tone. + return { tone: item.state === 'ok' || item.state === 'suspect' ? 'ok' : tone, key }; + } + const key = { ok: 'status.ok', suspect: 'status.suspect', failed: 'status.error' }[item.state] + ?? 'status.skipped'; + return { tone, key }; +} + +/** True for a package entry that turned out not to be a target. */ +export const isNonTarget = (entry) => entry.result?.info?.status === 'not_protected'; + +/** The entries of a package a run acted on: restored, unchanged, or failed. */ +export const targetEntries = (item) => + (item.entries ?? []).filter((entry) => isDone(entry) && !isNonTarget(entry)); + +/** Counts of finished inputs by outcome. */ +export function counts(items) { + const result = { all: items.length, ok: 0, suspect: 0, failed: 0, skipped: 0 }; + for (const item of items) if (isDone(item)) result[item.state] += 1; + return result; +} + +/** Every output kept in this tab, with the input it came from. */ +export function allOutputs(items = allItems()) { + const outputs = []; + for (const item of items) { + for (const source of [item, ...(item.entries ?? [])]) { + for (const output of source.result?.outputs ?? []) outputs.push({ item: source, output }); + } + } + return outputs; +} + +/** An output's path in the downloaded archive: under its folder's name. */ +export function archivePath(item, output) { + const group = item.group; + return group.kind === 'folder' ? `${group.name}/${output.path}` : output.path; +} + +/** The application context of a package archive's entries. */ +export function archiveAppKey(item, archive) { + if (!archive.identity) return `pkg:${item.id}:${archive.label}`; + const set = item.container.kind === 'apk' ? `dir:${dirName(item.relPath)}` : `bundle:${item.id}`; + return `pkg:${item.group.id}:${set}:${archive.identity[0]}:${archive.identity[1]}`; +} diff --git a/web/style.css b/web/style.css index 414e2ff..3aedd67 100644 --- a/web/style.css +++ b/web/style.css @@ -1,491 +1,542 @@ +/* Senbei in the browser. The look is the desktop workbench, measure for + measure: flat fills, 1px strokes, small radii, panels and tables. No + gradients, blur, or transitions. */ + +@font-face { + font-family: "Asul"; + src: url("assets/Asul-Bold.woff2") format("woff2"); + font-weight: 700; + font-display: swap; +} + :root { color-scheme: dark; --bg: #14161a; --panel: #1d2026; - --black: #0c0e11; + --panel-2: #23272e; + --well: #0c0e11; --border: #2e323b; + --border-strong: #3c414c; --text: #e4e7ec; --dim: #9aa3b0; + --faint: #808896; --accent: #e8b64c; + --accent-hover: #f0c463; + --accent-ink: #1a1408; --blue: #3b82f6; - --blue-deep: #1d4ed8; - --ok: #1e6b34; - --ok-bright: #6fcf7c; - --err: #7a2828; - --err-bright: #e06c6c; + --sel: rgba(59, 130, 246, 0.20); + --hover: rgba(255, 255, 255, 0.035); + --hover-fill: #2a2f37; + --hover-stroke: #566070; + --ok: #6fcf7c; + --ok-soft: rgba(111, 207, 124, 0.13); + --err: #e06c6c; + --err-soft: rgba(224, 108, 108, 0.13); --warn: #e8b64c; + --warn-soft: rgba(232, 182, 76, 0.13); + --skip: #8b93a1; + --info: #7aa7f7; + --info-soft: rgba(59, 130, 246, 0.14); + --r: 4px; + + --ui: "Segoe UI", system-ui, sans-serif; + --mono: "Cascadia Mono", Consolas, "DejaVu Sans Mono", Menlo, monospace; + --title: "Asul", var(--ui); } -* { box-sizing: border-box; } +/* The locale's own system font comes first, so Han characters and CJK + punctuation take that locale's glyphs. No CJK font is downloaded. */ +html[lang="zh-CN"] { --ui: "Microsoft YaHei UI", "Microsoft YaHei", "PingFang SC", "Noto Sans CJK SC", "Segoe UI", system-ui, sans-serif; } +html[lang="zh-TW"] { --ui: "Microsoft JhengHei UI", "Microsoft JhengHei", "PingFang TC", "Noto Sans CJK TC", "Segoe UI", system-ui, sans-serif; } +html[lang="ja"] { --ui: "Yu Gothic UI", "Meiryo UI", "Hiragino Sans", "Noto Sans CJK JP", "Segoe UI", system-ui, sans-serif; } +html[lang="ko"] { --ui: "Malgun Gothic", "Apple SD Gothic Neo", "Noto Sans CJK KR", "Segoe UI", system-ui, sans-serif; } -/* display rules below (inline-flex etc.) would otherwise beat the hidden - attribute's UA display:none — the badge/download icons must stay hidden. */ +* { box-sizing: border-box; } [hidden] { display: none !important; } +html, body { height: 100%; } body { margin: 0; background: var(--bg); color: var(--text); - font: 16px/1.55 system-ui, "Segoe UI", sans-serif; + font: 13.5px/18px var(--ui); + overflow: hidden; } +.mono, code { font-family: var(--mono), var(--ui); font-size: 12.5px; } +.dim { color: var(--dim); } +.faint { color: var(--faint); } +.spacer { flex: 1; } +a { color: var(--info); } -main { - max-width: 720px; - margin: 0 auto; - padding: 2.5rem 1.25rem 3rem; +/* ---------- controls ---------- */ + +button, select, input { font: inherit; color: inherit; } +button { + min-height: 26px; + padding: 3px 9px; + background: var(--panel-2); + border: 1px solid var(--border-strong); + border-radius: var(--r); + cursor: pointer; + white-space: nowrap; } +button:hover:not(:disabled) { background: var(--hover-fill); border-color: var(--hover-stroke); } +button:disabled { opacity: 0.5; cursor: default; } +button.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); font-weight: 600; } +button.primary:hover:not(:disabled) { background: var(--accent-hover); border-color: var(--accent-hover); } +button.primary:disabled { opacity: 1; background: rgba(232, 182, 76, 0.45); border-color: transparent; color: rgba(26, 20, 8, 0.7); } +/* A symbol takes one em whatever font it falls back to. */ +.ico { display: inline-block; width: 1em; text-align: center; } +/* A frameless button that shows its frame under the pointer. */ +button.ghost { min-height: 24px; background: transparent; border-color: transparent; color: var(--dim); font-size: 12px; line-height: 16px; } +button.ghost:hover:not(:disabled) { background: var(--hover-fill); border-color: var(--hover-stroke); } +select, input[type="search"], input[type="number"] { + height: 26px; + padding: 0 5px; + border: 1px solid var(--border-strong); + border-radius: var(--r); +} +select { min-width: 120px; background: var(--panel-2); cursor: pointer; } +select:hover { background: var(--hover-fill); border-color: var(--hover-stroke); } +input[type="search"], input[type="number"] { background: var(--well); } +input[type="search"]::placeholder { color: var(--faint); } +/* A check box is a small filled square with a thin tick. */ +input[type="checkbox"] { + appearance: none; flex: none; width: 14px; height: 14px; margin: 0; + background: var(--panel-2) center / 14px 14px no-repeat border-box; + border: 1px solid var(--border-strong); border-radius: var(--r); cursor: pointer; +} +input[type="checkbox"]:hover { background-color: var(--hover-fill); border-color: var(--hover-stroke); } +input[type="checkbox"]:checked { background-image: url("assets/check.svg"); } +:focus-visible { outline: 2px solid var(--blue); outline-offset: 1px; } +/* ---------- frame ---------- */ + +#app { display: grid; grid-template-rows: auto minmax(0, 1fr) auto; height: 100vh; height: 100dvh; } + +/* The bar's row is 26 tall where its buttons are; the settings button is 28. */ .topbar { - display: flex; - align-items: center; - justify-content: space-between; + display: flex; align-items: flex-start; flex-wrap: wrap; gap: 6px 8px; + min-height: 41px; padding: 6px 10px; + background: var(--panel); + border-bottom: 1px solid var(--border); + user-select: none; +} +.brand { display: flex; align-items: center; gap: 8px; height: 26px; margin-right: 6px; } +.brand img { width: 26px; height: 26px; } +.brand .word { font: 700 19px/22px var(--title); } +.brand .ver { color: var(--faint); font-size: 11.5px; line-height: 14px; } +.sep { width: 1px; height: 22px; margin-top: 2px; background: var(--border); } +.topbar > .spacer { height: 26px; } +.out-chip { + display: flex; align-items: center; gap: 6px; + min-width: 0; max-width: 340px; min-height: 24px; margin-top: 2px; padding: 0 7px; + background: transparent; border-color: var(--border); color: var(--dim); +} +.out-chip:hover:not(:disabled) { background: transparent; border-color: var(--hover-stroke); } +.out-chip b { color: var(--text); font-weight: 400; overflow: hidden; text-overflow: ellipsis; } +.gear { min-height: 28px; font-size: 15px; line-height: 20px; } + +.main { display: grid; grid-template-columns: 340px minmax(0, 1fr); min-height: 0; } +.main.blank { grid-template-columns: minmax(0, 1fr); } +.main.blank .inputs { display: none; } +@media (max-width: 1359px) { .main { grid-template-columns: 300px minmax(0, 1fr); } } + +/* ---------- inputs ---------- */ + +.inputs { + display: flex; flex-direction: column; min-height: 0; + background: var(--panel); + border-right: 1px solid var(--border); + user-select: none; +} +.inputs-head { display: grid; gap: 6px; padding: 8px 10px 10px; border-bottom: 1px solid var(--border); } +.inputs-head .title { display: flex; align-items: center; justify-content: space-between; min-height: 24px; font: 700 15px/18px var(--title); } +.inputs-head .title button { font-family: var(--ui); font-weight: 400; } +.chips { display: flex; flex-wrap: wrap; gap: 10px 4px; padding: 3px 0; } +.chip { + min-height: 18px; padding: 0.5px 7px; + background: transparent; border-color: var(--border); border-radius: 999px; + color: var(--dim); font-size: 12px; line-height: 15px; +} +.chip:hover:not(:disabled) { background: transparent; border-color: var(--border); } +.chip.on, .chip.on:hover:not(:disabled) { background: var(--sel); border-color: var(--blue); color: var(--text); } +.chip .n { margin-left: 4px; color: var(--faint); } +.chip.on .n { color: var(--dim); } +.search { width: 100%; } + +.list { flex: 1; overflow: auto; padding: 8px 0; } +.list > p { margin: 0; padding: 6px 10px; } +.caret { width: 14px; height: 14px; color: var(--faint); font-size: 9px; line-height: 14px; text-align: center; cursor: pointer; } + +.group-h { + position: relative; + display: grid; grid-template-columns: minmax(0, 1fr) auto; column-gap: 6px; + margin-top: 4px; padding: 5px 10px 4px 30px; + cursor: pointer; +} +.group-h:hover { background: var(--hover); } +.group-h.selected { background: var(--sel); } +.group-h .caret { position: absolute; left: 10px; top: 6px; } +.group-h .gname { font-size: 12.5px; font-weight: 600; line-height: 17px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.group-h .gcount { color: var(--faint); font-size: 12px; line-height: 17px; } +.group-h .gsub { grid-column: 1 / -1; color: var(--faint); font-size: 12px; line-height: 16px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.group-h.selected .gsub { color: var(--dim); } +.group-h .gsub.c-info { color: var(--info); } + +.row { + position: relative; + display: grid; grid-template-columns: minmax(0, 1fr) auto; column-gap: 8px; + height: 44px; padding: 5px 10px 4px 42px; + cursor: pointer; +} +.row:hover { background: var(--hover); } +.row.selected { background: var(--sel); box-shadow: inset 2px 0 0 var(--blue); } +.row .caret { position: absolute; left: 9px; top: 7px; } +.row .dot { position: absolute; left: 26px; top: 10px; } +.row .name { line-height: 20px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.row .tag { align-self: center; } +.row .meta { + grid-column: 1 / -1; display: flex; gap: 6px; min-width: 0; + color: var(--faint); font-size: 11.5px; line-height: 15px; white-space: nowrap; +} +.row.selected .meta { color: var(--dim); } +.row .meta .st, .row .meta .ex { min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.row .meta .time { flex: none; } +.row.nested { height: 42px; padding: 5px 10px 2px 60px; } +.row.nested .dot { left: 44px; } +.row.nested .meta { font-size: 11px; } +.row.others { + display: block; height: 24px; padding: 2px 10px 0 56px; + color: var(--faint); font-size: 11.5px; line-height: 16px; + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -h1 { margin-bottom: 0.25rem; } +.dot { display: inline-block; flex: none; width: 8px; height: 8px; border-radius: 50%; } +.dot.hollow { border: 1px solid var(--faint); } +.c-ok { color: var(--ok); } .bg-ok { background: var(--ok); } +.c-err { color: var(--err); } .bg-err { background: var(--err); } +.c-warn { color: var(--warn); } .bg-warn { background: var(--warn); } +.c-skip { color: var(--skip); } .bg-skip { background: var(--skip); } +.c-info { color: var(--info); } .bg-info { background: var(--info); } .tag { - font-size: 0.45em; - vertical-align: super; - color: var(--accent); - letter-spacing: 0.08em; + flex: none; padding: 0 4px; + border: 1px solid var(--border); border-radius: 3px; + color: var(--dim); font-size: 11px; line-height: 13px; white-space: nowrap; } +.tag.mono { font-size: 11px; } +.pill { + display: inline-block; flex: none; padding: 0.5px 7px; + border: 1px solid; border-radius: 999px; + font-size: 12px; line-height: 15px; white-space: nowrap; +} +.pill.ok { color: var(--ok); border-color: rgba(111, 207, 124, 0.45); background: var(--ok-soft); } +.pill.err { color: var(--err); border-color: rgba(224, 108, 108, 0.45); background: var(--err-soft); } +.pill.warn { color: var(--warn); border-color: rgba(232, 182, 76, 0.45); background: var(--warn-soft); } +.pill.info { color: var(--info); border-color: rgba(59, 130, 246, 0.45); background: var(--info-soft); } +.pill.skip { color: var(--skip); border-color: var(--border-strong); background: transparent; } -.github-link { +/* ---------- detail ---------- */ + +.detail { display: flex; flex-direction: column; min-width: 0; min-height: 0; } +.dhead { padding: 10px 16px 0; background: var(--bg); border-bottom: 1px solid var(--border); } +.dhead.notabs { padding-bottom: 6px; } +.dtitle { display: flex; align-items: center; gap: 10px; min-height: 24px; user-select: none; } +.dtitle h2 { flex: 0 1 auto; min-width: 80px; margin: 0; font-size: 17px; font-weight: 600; line-height: 22px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.dtitle .back { display: none; } +.dacts { display: flex; flex: none; gap: 4px; } +.dpath { margin-top: 4px; color: var(--faint); font-size: 12px; line-height: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.tabs { display: flex; gap: 2px; margin: 8px 0 -1px; user-select: none; } +.tab { + height: 30px; min-height: 0; padding: 2px 11px 0; + background: transparent; border-color: transparent; border-bottom: none; border-radius: var(--r) var(--r) 0 0; color: var(--dim); - transition: color 0.2s, transform 0.2s; } +.tab:hover:not(:disabled) { background: transparent; border-color: transparent; color: var(--text); } +.tab.on, .tab.on:hover:not(:disabled) { background: var(--panel); border-color: var(--border); color: var(--text); } +.tab .badge { margin-left: 4px; color: var(--faint); font-size: 11.5px; } -.github-link:hover { - color: var(--text); - transform: scale(1.12); -} +.dbody { flex: 1; min-height: 0; overflow: auto; background: var(--panel); container-type: inline-size; } +.dbody.flush { display: flex; flex-direction: column; overflow: hidden; } +.pad { padding: 18px 16px 24px; } +.pad > .note:first-child { margin-top: 0; } +.pick { flex: 1; display: grid; place-items: center; background: var(--panel); } -.lede { color: var(--dim); } -.lede strong { color: var(--text); } +.cards { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px 12px; } +@container (max-width: 791px) { .cards { grid-template-columns: minmax(0, 1fr); } } +.card { min-width: 0; padding: 10px 12px 12px; background: var(--bg); border: 1px solid var(--border); border-radius: 6px; } +.card.wide { grid-column: 1 / -1; } +.card h3 { display: flex; align-items: center; gap: 8px; min-height: 24px; margin: 0 0 8px; font: 700 14.5px/18px var(--title); } +.card h3 .aside { margin-left: auto; color: var(--faint); font: 400 12px/16px var(--ui); } -/* --- legal modal --- */ +/* The key column is as wide as its widest key, between 130 and 260. A key + sits at the top of its row; a plain value is centred in a row 24 tall. */ +.kv { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 3px 14px; } +.kv > .k { min-width: 130px; max-width: 260px; padding-top: 1px; color: var(--dim); } +.kv > .k > .room { display: block; height: 0; overflow: hidden; visibility: hidden; white-space: nowrap; user-select: none; } +.kv > .v { display: flex; flex-wrap: wrap; align-items: center; gap: 0 6px; min-width: 0; min-height: 24px; overflow-wrap: anywhere; } +.kv > .v > * { min-width: 0; max-width: 100%; } +.stack { display: grid; gap: 2px; justify-items: start; } +/* A line of monospace is as tall as its own text. */ +.stack > div:has(> .mono:only-child) { line-height: 15px; } +.flags { display: flex; flex-wrap: wrap; gap: 4px; } +.hash { display: flex; align-items: center; gap: 6px; } +.orow { display: flex; align-items: center; gap: 6px; } +.note { margin: 12px 0 0; color: var(--dim); font-size: 12px; line-height: 16px; } +.note:first-child, h3 + .note { margin-top: 0; } +.note + .msgs { margin-top: 12px; } -#legal-overlay { - position: fixed; - inset: 0; - z-index: 10; - display: flex; - align-items: center; - justify-content: center; - padding: 1.25rem; - background: rgba(10, 11, 13, 0.82); - backdrop-filter: blur(3px); - animation: fadeIn 0.25s ease-out; -} - -.legal-box { - max-width: 560px; - max-height: 85vh; - overflow-y: auto; - padding: 1.75rem 2rem; - background: var(--panel); - border: 1px solid var(--border); - border-radius: 12px; - animation: popIn 0.3s cubic-bezier(0.2, 1.4, 0.4, 1); -} - -.legal-box h2 { margin-top: 0; } -.legal-box p { color: var(--dim); font-size: 0.95rem; } -.legal-box strong { color: var(--text); } - -button { - font: inherit; - padding: 0.55rem 1.2rem; - border: 1px solid var(--accent); - border-radius: 8px; - background: var(--accent); - color: #14161a; - font-weight: 600; - cursor: pointer; - transition: transform 0.15s, box-shadow 0.15s, opacity 0.15s; -} - -button:not(:disabled):hover { - transform: translateY(-1px); - box-shadow: 0 3px 12px rgba(232, 182, 76, 0.25); -} - -button:not(:disabled):active { transform: translateY(0); } - -button:disabled { - opacity: 0.45; - cursor: default; -} - -button.secondary { - background: transparent; - color: var(--dim); - border-color: var(--border); -} - -button.secondary:not(:disabled):hover { - box-shadow: none; - color: var(--text); -} - -#legal-accept { width: 100%; margin-top: 0.5rem; } - -/* --- dropzone --- */ - -#dropzone { - margin: 1.5rem 0; - padding: 2.25rem 1.5rem; - text-align: center; - background: var(--panel); - border: 2px dashed var(--border); - border-radius: 12px; - cursor: pointer; - transition: border-color 0.2s, background 0.2s, transform 0.2s; -} - -#dropzone:hover, #dropzone:focus-visible { - border-color: var(--accent); - outline: none; -} - -#dropzone.over { - border-color: var(--accent); - background: #232730; - transform: scale(1.01); - animation: pulse 1s ease-in-out infinite; -} - -#dropzone p { margin: 0.25rem 0; } -.hint { color: var(--dim); font-size: 0.9rem; } -code { - background: var(--bg); - padding: 0.1em 0.35em; - border-radius: 4px; - font-size: 0.9em; -} - -/* --- file list --- */ - -#files { - list-style: none; - margin: 0 0 0.75rem; - padding: 0; -} - -.file { - position: relative; - margin-bottom: 0.45rem; - border: 1px solid var(--border); - border-radius: 8px; - overflow: hidden; - background: var(--black); /* staged */ - transition: background-color 0.5s ease; - animation: slideIn 0.25s ease-out; -} - -.file.leaving { - opacity: 0; - transform: translateX(12px); - margin-bottom: 0; - border-width: 0; - transition: - opacity 0.13s ease-in, - transform 0.13s ease-in, - max-height 0.17s ease-in 0.03s, - margin-bottom 0.17s ease-in 0.03s, - border-width 0.17s ease-in 0.03s; -} - -.file .bar { - position: absolute; - inset: 0; - opacity: 0; - transition: opacity 0.3s; -} - -.file.working { background: var(--black); } - -/* The gradient's left and right edge colors match, so the 200%-sized image - tiles seamlessly and the position loop has no visible restart. */ -.file.working .bar { - opacity: 1; - background: linear-gradient( - 100deg, - var(--blue-deep) 0%, - var(--blue) 25%, - #7fb3ff 50%, - var(--blue) 75%, - var(--blue-deep) 100% - ); - background-size: 200% 100%; - animation: shimmer 1.6s linear infinite; -} - -.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; - display: flex; - align-items: center; - gap: 0.6rem; - padding: 0.55rem 0.85rem; -} - -.file .name { - overflow-wrap: anywhere; - font-weight: 600; -} - -.file.working .name { color: #fff; } -.file.ok .name, .file.err .name, .file.blocked .name { color: #fff; } - -.badge.companion { - flex: none; - display: inline-flex; - align-items: center; - padding: 0.15rem 0.35rem; - border-radius: 5px; - background: rgba(59, 130, 246, 0.18); - color: #7fb3ff; -} - -.file.ok .badge.companion, -.file.err .badge.companion, -.file.working .badge.companion { - background: rgba(255, 255, 255, 0.15); - color: #fff; -} - -.file .status { - flex: 1; - text-align: right; - font-size: 0.85rem; - color: var(--dim); +.msgs { display: grid; gap: 6px; } +.msg { + display: grid; grid-template-columns: 14px minmax(0, 1fr); gap: 6px; + padding: 6px 8px; + background: var(--panel); border: 1px solid var(--border); border-radius: var(--r); overflow-wrap: anywhere; } +.msg.err { border-color: rgba(224, 108, 108, 0.4); } +.msg.warn { border-color: rgba(232, 182, 76, 0.4); } +.msg > span { padding-top: 1px; font-size: 13px; font-weight: 600; text-align: center; } -.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 { - flex: none; - display: inline-flex; - align-items: center; - justify-content: center; - width: 1.9rem; - height: 1.9rem; - border-radius: 6px; - background: rgba(255, 255, 255, 0.16); - color: #fff; - transition: background 0.15s, transform 0.15s; - animation: popIn 0.3s cubic-bezier(0.2, 1.4, 0.4, 1); +/* A folded part: a header with a small triangle, and under it, indented + beside a line, what it holds. `--head` is the header's height and `--gap` + the space under it. */ +details.fold { --head: 26px; --gap: 4px; position: relative; } +details.fold > summary { + position: relative; display: flex; align-items: center; width: fit-content; height: var(--head); + padding: 0 10px 0 18px; list-style: none; cursor: pointer; } - -.file .dl:hover { - background: rgba(255, 255, 255, 0.32); - transform: scale(1.1); +details.fold > summary::-webkit-details-marker { display: none; } +details.fold > summary::before { + content: ""; position: absolute; left: 6px; top: calc(50% - 3px); width: 6px; height: 6px; + background: var(--text); clip-path: polygon(0 0, 100% 50%, 0 100%); } - -.file .remove { - flex: none; - padding: 0.1rem 0.55rem; - background: transparent; - border: 1px solid var(--border); - border-radius: 6px; - color: var(--dim); - font-weight: 400; +details.fold[open] > summary::before { clip-path: polygon(0 0, 100% 0, 50% 100%); } +details.fold[open]::after { + content: ""; position: absolute; left: 9px; top: calc(var(--head) + var(--gap)); bottom: 2px; + width: 1px; background: var(--border); } +details.fold > pre { margin: var(--gap) 0 0 18px; line-height: 15px; } +details.tech { --head: 24px; --gap: 6px; margin-top: 6px; } +details.tech > summary { color: var(--faint); font-size: 12px; } +details.tech > pre { color: var(--dim); white-space: pre-wrap; } -.file .remove:hover { - color: var(--err-bright); - border-color: var(--err-bright); - box-shadow: none; - transform: none; +.route { padding: 10px 0; } +.route + .route { border-top: 1px solid var(--border); } +.route:first-of-type { padding-top: 6px; } +.route:last-of-type { padding-bottom: 2px; } +.rhead { display: flex; align-items: center; gap: 12px; min-height: 24px; } +.route .msgs { margin-top: 8px; } +.star { color: var(--warn); font-size: 12px; } + +.stages { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } +.stage { min-width: 142px; padding: 5px 10px; background: var(--panel); border: 1px solid var(--border); border-radius: var(--r); } +.stage.dimmed { opacity: 0.5; } +.sname { display: flex; align-items: center; gap: 6px; min-height: 24px; font-size: 12.5px; font-weight: 600; } +.sicon { min-width: 12px; } +.sdur { color: var(--faint); font-size: 12px; font-weight: 400; } +.sstat { margin-top: 1px; font-size: 12px; line-height: 16px; } +.sdet { max-width: 360px; margin-top: 1px; color: var(--dim); font-size: 12px; line-height: 16px; overflow-wrap: anywhere; } +.arrow { color: var(--faint); } + +.action { display: grid; grid-template-columns: minmax(110px, max-content) minmax(0, 1fr); gap: 10px; align-items: start; padding: 6px 0; } + +/* Tables: dim headers, no rules between rows, a capped height with its own + scroll. Columns have set widths and cut what does not fit; they are 8 + apart, with a line in the gap except beside the column that grows. The + scrollbar's room is kept whether it shows or not, so columns do not move + when rows are added. */ +.tbl-wrap { max-height: 550px; overflow: auto; scrollbar-gutter: stable; border: 1px solid var(--border); border-radius: var(--r); } +table.t { width: 100%; border-collapse: separate; border-spacing: 0; table-layout: fixed; } +table.t th, table.t td { padding: 4px; line-height: 16px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +table.t th { + position: sticky; top: 0; z-index: 1; height: 26px; padding-bottom: 0; vertical-align: top; + background: var(--bg); color: var(--dim); font-size: 12px; font-weight: 400; text-align: left; } +table.t td { height: 24px; vertical-align: middle; } +/* Rows are 4 apart, which each row shares with its neighbours; the last row + has no neighbour below. */ +table.t tbody tr:last-child > td { height: 22px; padding-bottom: 2px; } +table.t tr > :first-child { padding-left: 0; } +table.t tr > :last-child { padding-right: 0; } +table.t tr > :not(:last-child) { border-right: 1px solid var(--border); } +table.t.grow-2 tr > :nth-child(2) { border-right: none; } +table.t tr[data-act] { cursor: pointer; } +table.t tr[data-act]:hover td { background: var(--hover-fill); } +table.t th.num, table.t td.num { text-align: right; } +table.t td.num, table.t td.mono, table.t td .mono { font-family: var(--mono), var(--ui); font-size: 12px; } +table.t td.c-dot { line-height: 0; } +table.t td > div { overflow: hidden; text-overflow: ellipsis; } +/* Rows of two lines. A cell that holds two starts them at the row's top. */ +table.t.tall td { height: 40px; } +table.t.tall tbody tr:last-child > td { height: 38px; } +table.t td.two, table.t.tall tbody tr:last-child > td.two { padding-top: 2px; padding-bottom: 0; vertical-align: top; } +table.t td.two > div { line-height: 18px; } +table.t td.two > .mono { line-height: 14px; } +table.t td.two > .place { line-height: 16px; } +.place { color: var(--faint); font-size: 12px; } +.check { display: flex; align-items: center; gap: 4px; width: fit-content; min-height: 24px; margin-bottom: 12px; cursor: pointer; } +details.inv { margin-top: 16px; } +details.inv > summary { color: var(--dim); } +pre.well { max-height: 296px; padding: 8px 10px; overflow: auto; background: var(--well); border-radius: var(--r); } -.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); +/* ---------- log ---------- */ + +.logbar { display: flex; align-items: center; gap: 8px; padding: 13px 12px 12px; border-bottom: 1px solid var(--border); user-select: none; } +.seg { display: inline-flex; border: 1px solid var(--border-strong); border-radius: var(--r); overflow: hidden; } +.seg button { height: 22px; min-height: 0; padding: 0 10px; background: transparent; border: none; border-radius: 0; } +.seg button + button { border-left: 1px solid var(--border-strong); } +.seg button:hover:not(:disabled) { background: var(--hover); } +.seg button.on, .seg button.on:hover:not(:disabled) { background: var(--sel); } +.log { font-family: var(--mono), var(--ui); font-size: 12.5px; line-height: 16px; } +.dbody.flush > .log { flex: 1; min-height: 0; overflow: auto; padding: 11px 12px 6px; } +.logline { display: grid; grid-template-columns: 96px 56px minmax(0, 1fr); column-gap: 10px; } +.logline .ts { color: var(--faint); } +.logline .lv { font-family: var(--ui); font-size: 11.5px; } +.logline .tx { white-space: pre-wrap; overflow-wrap: anywhere; } +.logline.detail { font-size: 12px; } +.logline.detail .tx { padding-left: 14px; color: var(--dim); } + +/* ---------- empty state and drop ---------- */ + +.empty { flex: 1; display: grid; place-items: center; padding: 30px; overflow: auto; background: var(--bg); } +/* Dashes 6 long and 4 apart, with square corners. */ +.drop, .dragover .box { + --dash: var(--border-strong); + --dash-w: 1.5px; + background: + repeating-linear-gradient(90deg, var(--dash) 0 6px, transparent 6px 10px) top / 100% var(--dash-w) no-repeat, + repeating-linear-gradient(90deg, var(--dash) 0 6px, transparent 6px 10px) bottom / 100% var(--dash-w) no-repeat, + repeating-linear-gradient(0deg, var(--dash) 0 6px, transparent 6px 10px) left / var(--dash-w) 100% no-repeat, + repeating-linear-gradient(0deg, var(--dash) 0 6px, transparent 6px 10px) right / var(--dash-w) 100% no-repeat, + var(--bg); } +.drop { width: min(640px, 100%); min-height: 330px; padding: 30px; text-align: center; } +.drop img { display: block; width: 84px; height: 84px; margin: 0 auto; } +.drop h2 { margin: 12px 0 0; font: 700 21px/25px var(--title); } +.drop .kinds { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 6px; min-height: 24px; margin-top: 14px; } +.drop .acts { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; margin-top: 18px; } +.drop p { margin: 20px 0 0; } +.dragover { position: fixed; inset: 0; z-index: 30; display: grid; place-items: center; background: rgba(12, 14, 17, 0.78); pointer-events: none; } +.dragover .box { --dash: var(--accent); --dash-w: 2px; padding: 40px 70px; } +.dragover .box h2 { margin: 0; color: var(--accent); font: 700 22px/27px var(--title); } -.file.ok .remove:hover, -.file.err .remove:hover { - color: #fff; - border-color: #fff; +/* ---------- status bar ---------- */ + +.statusbar { + display: flex; align-items: center; gap: 14px; + min-height: 33px; padding: 4px 12px; + background: var(--panel); border-top: 1px solid var(--border); + color: var(--dim); font-size: 12px; white-space: nowrap; + user-select: none; } +.status-line { display: flex; flex: 1; align-items: center; gap: 14px; min-width: 0; overflow: hidden; } +.status-line > :first-child { font-size: 13.5px; } +.status-line b { color: var(--text); font-size: 12.5px; font-weight: 600; } +.progress { flex: none; width: 220px; height: 8px; overflow: hidden; background: var(--well); border: 1px solid var(--border); border-radius: 4px; } +.progress > div { height: 100%; background: var(--accent); border-radius: 4px; } +.status-line .cur { flex: 0 1 auto; min-width: 0; max-width: 420px; color: var(--text); font-size: 12px; overflow: hidden; text-overflow: ellipsis; } +.status-line .step, .status-line .notice { min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.cancel { flex: none; color: var(--err); font-size: 13.5px; } -.actions { - display: flex; - gap: 0.6rem; - animation: fadeIn 0.25s ease-out; +/* ---------- menus ---------- */ + +.ctx { + position: fixed; z-index: 35; + display: grid; gap: 4px; + min-width: 200px; max-width: min(340px, calc(100vw - 16px)); padding: 4px; + background: var(--panel); border: 1px solid var(--border-strong); border-radius: 6px; + box-shadow: 6px 10px 8px rgba(0, 0, 0, 0.38); + user-select: none; } - -/* --- 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); +.ctx-item { + display: flex; align-items: flex-start; gap: 6px; + width: 100%; min-height: 24px; padding: 2px 1px; + background: transparent; border-color: transparent; + text-align: left; white-space: normal; } +.ctx-item:hover:not(:disabled) { background: var(--hover-fill); border-color: transparent; } +.ctx-item .radio { flex: none; width: 12px; color: var(--accent); text-align: center; } +.ctx-item .sub { display: block; color: var(--faint); font-size: 12px; line-height: 16px; overflow-wrap: anywhere; } +.ctx-item .kbd { margin-left: auto; padding-left: 16px; color: var(--faint); } +.ctx-sep { height: 1px; margin: 1px 0; background: var(--border); } +.ctx-note { margin: 0; padding: 0 2px 2px; color: var(--faint); font-size: 12px; line-height: 16px; } -.limits label { flex: none; } +/* ---------- dialogs ---------- */ -#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; +dialog.modal { + width: min(620px, calc(100vw - 40px)); max-height: calc(100dvh - 40px); + padding: 0; color: var(--text); + background: var(--panel); border: 1px solid var(--border-strong); border-radius: 8px; } - -#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); - font-size: 0.85rem; -} -footer a { color: var(--dim); } - -/* --- narrow screens --- */ - -/* On a narrow viewport the status column (flex: 1, right-aligned) is - squeezed by a long file name into a one-word-per-line vertical strip. - Stack the row instead: name + icons on the first line, the status on its - own full-width line below, left-aligned. */ -@media (max-width: 560px) { - main { padding: 1.5rem 0.9rem 2.5rem; } - - #dropzone { padding: 1.75rem 1rem; } - - .file .row { flex-wrap: wrap; } - .file .name { flex: 1; min-width: 0; } - .file .status { - order: 6; /* after the download/remove icons */ - flex-basis: 100%; - text-align: left; - } -} - -/* --- animations --- */ - -@keyframes fadeIn { - from { opacity: 0; } - to { opacity: 1; } -} - -@keyframes popIn { - from { opacity: 0; transform: scale(0.85); } - to { opacity: 1; transform: scale(1); } -} - -@keyframes slideIn { - from { opacity: 0; transform: translateY(-6px); } - to { opacity: 1; transform: translateY(0); } -} - -@keyframes shimmer { - from { background-position: 0 0; } - to { background-position: -200% 0; } -} - -@keyframes pulse { - 0%, 100% { box-shadow: 0 0 0 0 rgba(232, 182, 76, 0.25); } - 50% { box-shadow: 0 0 0 6px rgba(232, 182, 76, 0); } -} - +dialog#settings { width: min(760px, calc(100vw - 40px)); } +dialog.modal[open] { display: flex; flex-direction: column; } +dialog.modal::backdrop { background: rgba(8, 9, 11, 0.72); } +dialog.modal, dialog.modal::backdrop { transition: opacity 200ms ease; } @media (prefers-reduced-motion: reduce) { - *, *::before, *::after { - animation-duration: 0.01ms !important; - animation-iteration-count: 1 !important; - transition-duration: 0.01ms !important; - } + /* Keep the opacity-only fade, but make the transition shorter. */ + dialog.modal, dialog.modal::backdrop { transition-duration: 100ms; } +} +dialog.modal:is(.opening, [inert]), dialog.modal:is(.opening, [inert])::backdrop { opacity: 0; } +.modal-h { display: flex; align-items: center; gap: 10px; padding: 12px 16px; border-bottom: 1px solid var(--border); } +.modal-h img { width: 24px; height: 24px; } +.modal-h h2 { margin: 0; font: 700 17px/22px var(--title); } +.modal-b { padding: 14px 16px; overflow: auto; } +.modal-b p { margin: 0 0 10px; color: var(--dim); } +.modal-b p:last-child { margin-bottom: 0; } +.modal-b p strong { color: var(--text); font-weight: 600; } +.modal-f { display: flex; align-items: center; gap: 8px; padding: 10px 16px; border-top: 1px solid var(--border); } + +.set-body { display: flex; flex: 1; min-height: 380px; overflow: hidden; } +.set-nav { display: flex; flex: none; flex-direction: column; gap: 2px; width: 160px; padding: 8px 6px; border-right: 1px solid var(--border); } +.nav { height: 26px; min-height: 0; padding: 0 9px; background: transparent; border-color: transparent; color: var(--dim); text-align: left; } +.nav:hover:not(:disabled) { background: var(--hover); border-color: transparent; } +.nav.on, .nav.on:hover:not(:disabled) { background: var(--sel); color: var(--text); } +.set-pane { display: grid; flex: 1; align-content: start; gap: 12px; min-width: 0; padding: 12px 16px; overflow: auto; } +.set-pane > p { margin: 0; } +.field { display: grid; grid-template-columns: 210px minmax(0, 1fr); column-gap: 14px; align-items: start; } +.field > label, .field > .flabel { display: flex; align-items: center; min-height: 24px; } +.field .control { display: flex; align-items: center; gap: 8px; min-height: 24px; } +.field .help { margin: 4px 0 0; color: var(--faint); font-size: 12px; line-height: 16px; } +.field input[type="number"] { width: 90px; } +#set-output { width: 260px; max-width: 100%; } +.about { display: flex; align-items: center; gap: 14px; } +.about img { width: 72px; height: 72px; } +.about .word { font: 700 22px/27px var(--title); } + +::-webkit-scrollbar { width: 14px; height: 14px; } +::-webkit-scrollbar-thumb { background: #353a44; border: 2px solid transparent; border-radius: 7px; background-clip: padding-box; } +::-webkit-scrollbar-track, ::-webkit-scrollbar-corner { background: transparent; } + +/* ---------- narrow windows: one pane at a time ---------- */ + +@media (max-width: 760px) { + .main, .main.blank { grid-template-columns: minmax(0, 1fr); } + .main .detail { display: none; } + .main.blank .detail { display: flex; } + .main.show-detail .inputs { display: none; } + .main.show-detail .detail { display: flex; } + .inputs { border-right: none; } + .dtitle { flex-wrap: wrap; } + .dtitle .back { display: inline-block; min-width: 32px; } + .brand .ver, .topbar .sep, .out-chip > span:first-child { display: none; } + .out-chip { max-width: 190px; } + .topbar button, .dtitle button { min-height: 32px; } + .pad { padding: 12px 10px 20px; } + .dhead { padding: 8px 10px 0; } + .kv > .k { min-width: 96px; max-width: 40vw; } + .action { grid-template-columns: minmax(0, 1fr); } + .progress { width: 90px; } + .status-line .step { display: none; } + .logline { grid-template-columns: 84px 40px minmax(0, 1fr); column-gap: 6px; } + .dbody.flush > .log { padding: 8px; } + .drop { padding: 22px 14px; } + .row { height: 48px; padding-top: 7px; } + .row .dot { top: 12px; } + .row .caret { top: 9px; } + .row.nested { height: 46px; } + .set-body { flex-direction: column; min-height: 0; overflow: auto; } + .set-nav { flex-direction: row; width: auto; border-right: none; border-bottom: 1px solid var(--border); overflow: auto; } + .set-pane { overflow: visible; } + .field { grid-template-columns: minmax(0, 1fr); } } diff --git a/web/tests/archives.js b/web/tests/archives.js new file mode 100644 index 0000000..1ddf68c --- /dev/null +++ b/web/tests/archives.js @@ -0,0 +1,69 @@ +// Hand-built ZIP archives for the tests, so that a test can state exactly +// what an archive declares, including what a well-behaved writer never would. + +import { deflateRawSync } from 'node:zlib'; +import { crc32 } from '../zip.js'; + +const encoder = new TextEncoder(); + +/** + * Build an archive from `files`. + * + * Each file is `{ name, data, deflate, flags, crc, size, encrypted }`. `data` + * is a string or bytes. `crc` and `size` override what the directory declares. + */ +export function makeZip(files) { + const parts = []; + const central = []; + let offset = 0; + for (const file of files) { + const name = encoder.encode(file.name); + const data = typeof file.data === 'string' ? encoder.encode(file.data) : (file.data ?? new Uint8Array()); + const stored = file.deflate ? new Uint8Array(deflateRawSync(data)) : data; + const flags = (file.flags ?? 0x800) | (file.encrypted ? 1 : 0); + const crc = file.crc ?? crc32(data); + const size = file.size ?? data.length; + + const local = new DataView(new ArrayBuffer(30 + name.length)); + local.setUint32(0, 0x04034b50, true); + local.setUint16(4, 20, true); + local.setUint16(6, flags, true); + local.setUint16(8, file.deflate ? 8 : 0, true); + local.setUint32(14, crc, true); + local.setUint32(18, stored.length, true); + local.setUint32(22, size, true); + local.setUint16(26, name.length, true); + new Uint8Array(local.buffer).set(name, 30); + + const record = new DataView(new ArrayBuffer(46 + name.length)); + record.setUint32(0, 0x02014b50, true); + record.setUint16(4, 20, true); + record.setUint16(6, 20, true); + record.setUint16(8, flags, true); + record.setUint16(10, file.deflate ? 8 : 0, true); + record.setUint32(16, crc, true); + record.setUint32(20, stored.length, true); + record.setUint32(24, size, true); + record.setUint16(28, name.length, true); + record.setUint32(42, offset, true); + new Uint8Array(record.buffer).set(name, 46); + + parts.push(local.buffer, stored); + central.push(record.buffer); + offset += local.byteLength + stored.length; + } + const directorySize = central.reduce((sum, record) => sum + record.byteLength, 0); + const end = new DataView(new ArrayBuffer(22)); + end.setUint32(0, 0x06054b50, true); + end.setUint16(8, files.length, true); + end.setUint16(10, files.length, true); + end.setUint32(12, directorySize, true); + end.setUint32(16, offset, true); + return new Blob([...parts, ...central, end.buffer]); +} + +export async function bytesOf(blob) { + return new Uint8Array(await blob.arrayBuffer()); +} + +export const text = (bytes) => new TextDecoder().decode(bytes); diff --git a/web/tests/model.test.js b/web/tests/model.test.js new file mode 100644 index 0000000..b82a5d3 --- /dev/null +++ b/web/tests/model.test.js @@ -0,0 +1,208 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { test } from 'node:test'; + +import { + MAX_LIMIT_MIB, + MIN_LIMIT_MIB, + ModuleContext, + candidateKind, + embeddedMetadataPath, + escapesRoot, + formatBytes, + formatClock, + formatCount, + formatDuration, + isCompanionName, + isNestedPackage, + isOutputDir, + isPackageTarget, + languageFor, + localClock, + looseAppRoot, + outName, + parseLimitMiB, + safeEntryPath, + shortHash, + sniff, + stateOf, +} from '../model.js'; +import { VERSION } from '../state.js'; + +const MIB = 1024 * 1024; + +test('a folder scan opens only the names that can be targets', () => { + assert.equal(candidateKind('bin/Game.EXE'), 'pe'); + assert.equal(candidateKind('plugin.dll'), 'pe'); + assert.equal(candidateKind('lib/arm64-v8a/libil2cpp.so'), 'so'); + assert.equal(candidateKind('Data/Global-Metadata.dat'), 'metadata'); + assert.equal(candidateKind('app.apk'), 'package'); + assert.equal(candidateKind('app.apks'), 'package'); + assert.equal(candidateKind('app.xapk'), 'package'); + for (const name of ['data.unity3d', 'sharedassets0.assets', 'level.dat', 'movie.mp4', 'noext', 'a.dll._']) { + assert.equal(candidateKind(name), null, name); + } +}); + +test('companion payloads are recognised by name', () => { + assert.ok(isCompanionName('Game.exe._')); + assert.ok(isCompanionName('plugin.DLL._')); + assert.ok(!isCompanionName('plugin.dll')); + assert.ok(!isCompanionName('libil2cpp.so._')); + assert.ok(!isCompanionName('._')); +}); + +test('a previous output tree is not entered', () => { + assert.ok(isOutputDir('unpack')); + assert.ok(isOutputDir('Unpack')); + assert.ok(!isOutputDir('unpacked')); +}); + +test('sniff reads the magic of each input kind', () => { + const elf = new Uint8Array(64); + elf.set([0x7f, 0x45, 0x4c, 0x46, 2, 1]); + elf[18] = 0xb7; + assert.deepEqual(sniff(elf), { zip: false, metadata: false, mz: false, elf64Aarch64: true }); + elf[18] = 0x3e; + assert.equal(sniff(elf).elf64Aarch64, false); + assert.equal(sniff(new Uint8Array([0x4d, 0x5a, 0x90])).mz, true); + assert.equal(sniff(new Uint8Array([0x50, 0x4b, 3, 4])).zip, true); + assert.equal(sniff(new Uint8Array([0xaf, 0x1b, 0xb1, 0xfa])).metadata, true); + assert.deepEqual(sniff(new Uint8Array()), { zip: false, metadata: false, mz: false, elf64Aarch64: false }); +}); + +test('outputs are named as the native tools name them', () => { + assert.equal(outName('Game.exe'), 'Game.unpack.exe'); + assert.equal(outName('lib/arm64-v8a/libil2cpp.so'), 'lib/arm64-v8a/libil2cpp.unpack.so'); + assert.equal(outName('a.b/noext'), 'a.b/noext.unpack'); + assert.equal(outName('global-metadata.dat'), 'global-metadata.unpack.dat'); + assert.equal( + embeddedMetadataPath('app.apk/lib/arm64-v8a/libil2cpp.unpack.so'), + 'app.apk/lib/arm64-v8a/global-metadata.unpack.dat', + ); + assert.equal(embeddedMetadataPath('libil2cpp.unpack.so'), 'global-metadata.unpack.dat'); +}); + +test('loose Android files are paired only through their application layout', () => { + assert.equal(looseAppRoot('lib/arm64-v8a/libil2cpp.so', 'so'), ''); + assert.equal(looseAppRoot('game/lib/arm64-v8a/libil2cpp.so', 'so'), 'game'); + assert.equal(looseAppRoot('game/LIB/arm64-v8a/libil2cpp.so', 'so'), 'game'); + assert.equal(looseAppRoot('game/libil2cpp.so', 'so'), null); + assert.equal(looseAppRoot('game/assets/bin/Data/Managed/Metadata/global-metadata.dat', 'metadata'), 'game'); + assert.equal(looseAppRoot('assets/global-metadata.dat', 'metadata'), ''); + assert.equal(looseAppRoot('game/global-metadata.dat', 'metadata'), null); + assert.equal(looseAppRoot('game/Game.exe', 'pe'), null); +}); + +test('package entry names that leave the package are refused', () => { + assert.equal(safeEntryPath('lib/arm64-v8a/libil2cpp.so'), 'lib/arm64-v8a/libil2cpp.so'); + assert.equal(safeEntryPath('./lib//x.so'), 'lib/x.so'); + assert.equal(safeEntryPath('lib\\x.so'), 'lib/x.so'); + for (const name of ['../x.so', 'lib/../../x.so', '/abs/x.so', 'C:/x.so', 'c:x.so', '', '.', 'a\0b', null]) { + assert.equal(safeEntryPath(name), null, String(name)); + } +}); + +test('only libraries and metadata are read from a package', () => { + assert.ok(isPackageTarget('lib/arm64-v8a/libmain.so')); + assert.ok(isPackageTarget('assets/bin/Data/Managed/Metadata/global-metadata.dat')); + assert.ok(!isPackageTarget('classes.dex')); + assert.ok(!isPackageTarget('assets/Game.exe')); + assert.ok(!isPackageTarget('base.apk')); + assert.ok(isNestedPackage('splits/base.apk')); + assert.ok(!isNestedPackage('inner.xapk')); +}); + +test('the limit setting accepts whole MiB in its range', () => { + assert.equal(parseLimitMiB('64'), 64 * MIB); + assert.equal(parseLimitMiB(' 64.4 '), 64 * MIB); + assert.equal(parseLimitMiB(String(MIN_LIMIT_MIB)), MIN_LIMIT_MIB * MIB); + assert.equal(parseLimitMiB(String(MAX_LIMIT_MIB)), MAX_LIMIT_MIB * MIB); + const fallback = 123; + for (const raw of ['', null, 'abc', '0', '-5', String(MIN_LIMIT_MIB - 1), String(MAX_LIMIT_MIB + 1), 'Infinity']) { + assert.equal(parseLimitMiB(raw, fallback), fallback, String(raw)); + } +}); + +test('the page language follows the browser languages', () => { + assert.equal(languageFor(['fr-FR', 'ja-JP']), 'ja'); + assert.equal(languageFor(['zh-TW']), 'zh-TW'); + assert.equal(languageFor(['zh-HK']), 'zh-TW'); + assert.equal(languageFor(['zh-Hant-CN']), 'zh-TW'); + assert.equal(languageFor(['zh']), 'zh-CN'); + assert.equal(languageFor(['zh_Hans_TW']), 'zh-CN'); + assert.equal(languageFor(['ko-KR']), 'ko'); + assert.equal(languageFor(['de']), 'en'); + assert.equal(languageFor(undefined), 'en'); +}); + +test('a report maps to the state its input is shown in', () => { + assert.equal(stateOf({ status: 'recovered', profile: { static_validation: 'clean' } }), 'ok'); + assert.equal(stateOf({ status: 'recovered', suspect: true, profile: {} }), 'suspect'); + assert.equal(stateOf({ status: 'recovered', profile: { static_validation: 'warnings' } }), 'suspect'); + assert.equal(stateOf({ status: 'recovered', profile: { static_validation: 'failed' } }), 'suspect'); + for (const status of ['unchanged', 'unsupported', 'not_protected']) { + assert.equal(stateOf({ status }), 'skipped'); + } + assert.equal(stateOf({ status: 'failed' }), 'failed'); + assert.equal(stateOf(null), 'failed'); +}); + +test('module 0x0C binds only when an application has exactly one', () => { + const context = new ModuleContext(); + assert.equal(context.count, 0); + assert.equal(context.module, null); + context.add(new Uint8Array([1, 2, 3])); + context.add(new Uint8Array([1, 2, 3])); + context.add(new Uint8Array()); + context.add(null); + assert.equal(context.count, 1); + assert.deepEqual(context.module, new Uint8Array([1, 2, 3])); + context.add(new Uint8Array([1, 2, 4])); + assert.equal(context.count, 2); + assert.equal(context.module, null); +}); + +test('sizes, durations, counts, and hashes are written as the workbench writes them', () => { + assert.equal(formatBytes(0), '0 B'); + assert.equal(formatBytes(1023), '1023 B'); + assert.equal(formatBytes(1536), '1.5 KiB'); + assert.equal(formatBytes(5 * MIB), '5.0 MiB'); + assert.equal(formatBytes(3 * 1024 * MIB), '3.00 GiB'); + assert.equal(formatBytes(NaN), '0 B'); + assert.equal(formatDuration(12.4), '12 ms'); + assert.equal(formatDuration(999.6), '1.00 s'); + assert.equal(formatDuration(3700), '3.70 s'); + assert.equal(formatDuration(125_000), '125.00 s'); + assert.equal(formatDuration(-1), ''); + assert.equal(formatClock(0), '0:00.0'); + assert.equal(formatClock(1499), '0:01.4'); + assert.equal(formatClock(61_950), '1:01.9'); + assert.equal(formatClock(-5), '0:00.0'); + assert.equal(formatCount(0), '0'); + assert.equal(formatCount(999), '999'); + assert.equal(formatCount(12345), '12,345'); + assert.equal(formatCount(1234567), '1,234,567'); + assert.equal(formatCount(null), ''); + const sha256 = '66b8232752ea82ba0123456789abcdef0123456789abcdef0123456775aa29ff'; + assert.equal(shortHash(sha256), '66b8232752ea82ba…75aa29ff'); + assert.equal(shortHash('short'), 'short'); + assert.equal(shortHash(null), ''); + assert.equal(localClock(new Date(2026, 0, 2, 3, 4, 5, 6).getTime()), '03:04:05.006'); + assert.equal(localClock(new Date(2026, 0, 2, 13, 46, 42, 936).getTime()), '13:46:42.936'); +}); + +test('an entry name that would leave its package is told apart from the rest', () => { + for (const name of ['../escape.so', 'lib/../../x.so', '/abs/libil2cpp.so', 'C:/x.so', 'c:\\x.so', '\\\\host\\x.so', 'a\0b.so']) { + assert.ok(escapesRoot(name), name); + } + for (const name of ['lib/arm64-v8a/libil2cpp.so', 'lib/./x.so', 'a/../b.so', 'assets/..hidden/x.so', '']) { + assert.ok(!escapesRoot(name), name); + } +}); + +test('the page shows the version of the engine it ships', () => { + const manifest = readFileSync(new URL('../../senbei-wasm/Cargo.toml', import.meta.url), 'utf8'); + const version = /^version\s*=\s*"([^"]+)"/m.exec(manifest)?.[1]; + assert.equal(VERSION, version); +}); diff --git a/web/tests/output.test.js b/web/tests/output.test.js new file mode 100644 index 0000000..775b000 --- /dev/null +++ b/web/tests/output.test.js @@ -0,0 +1,153 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { FolderWriter, downloadArchive } from '../output.js'; +import { state } from '../state.js'; +import { entryBlob, entrySource, openZip } from '../zip.js'; + +function directory(writes, { rejectZip = false, rejectLog = false, same = false } = {}, prefix = '') { + return { + isSameEntry: async () => same, + getDirectoryHandle: async (name) => directory(writes, { rejectZip, rejectLog, same }, `${prefix}${name}/`), + async getFileHandle(name) { + if (name.toLowerCase().endsWith('.dll')) throw new TypeError('file name refused'); + if (rejectZip && name.endsWith('.zip')) throw new Error('archive write denied'); + if (rejectLog && name.endsWith('.log')) throw new Error('log write denied'); + return { + async createWritable() { + let content; + return { + async write(blob) { + if (name.endsWith('.error')) throw new TypeError('write failed after opening the file'); + content = blob; + }, + async close() { writes.set(`${prefix}${name}`, content); }, + async abort() {}, + }; + }, + }; + }, + }; +} + +const output = (path, content) => ({ path, blob: new Blob([content]) }); +const fixedDate = new Date('2026-01-02T03:04:05.678Z'); + +function record(group, ...outputs) { + return { group, result: { outputs }, log: [] }; +} + +test('ZIP downloads include the full log for every input, even a failure with no output', async () => { + const group = { kind: 'files' }; + const recovered = record(group, output('app.unpack.exe', 'recovered image')); + const failed = record(group); + recovered.log.push({ at: fixedDate.getTime(), level: 'detail', text: 'engine step detail' }); + failed.log.push({ at: fixedDate.getTime(), level: 'error', text: 'unreadable input' }); + state.logLevel = 'problems'; + try { + const { name, blob } = await downloadArchive([recovered, failed], fixedDate); + assert.equal(name, 'senbei-unpack.20260102-030405.zip'); + const { entries } = await openZip(blob); + assert.deepEqual(entries.map((entry) => entry.name), ['app.unpack.exe', 'senbei-20260102-030405.log']); + const log = await entryBlob(await entrySource(blob, entries[1]), 1024); + assert.match(await log.text(), /engine step detail\n.*unreadable input/); + } finally { + state.logLevel = 'all'; + } +}); + +test('folder output includes an unfiltered log even when no files were recovered', async () => { + const writes = new Map(); + const writer = new FolderWriter(directory(writes)); + const group = { kind: 'files' }; + const failed = record(group); + failed.log.push({ at: fixedDate.getTime(), level: 'detail', text: 'engine step detail' }); + failed.log.push({ at: fixedDate.getTime(), level: 'error', text: 'unreadable input' }); + await writer.saveLog([record(group)], fixedDate); + assert.equal(writes.size, 0); + state.logLevel = 'problems'; + try { + await writer.saveLog([failed], fixedDate); + assert.deepEqual([...writes.keys()], ['unpack/senbei-20260102-030405-678.log']); + assert.match(await [...writes.values()][0].text(), /engine step detail\n.*unreadable input/); + } finally { + state.logLevel = 'all'; + } +}); + +test('a failed log write leaves recovery outputs and their logs intact', async () => { + const writes = new Map(); + const writer = new FolderWriter(directory(writes, { rejectLog: true })); + const file = output('app.unpack.exe', 'exe bytes'); + const item = record({ kind: 'files' }, file); + item.log.push({ at: fixedDate.getTime(), level: 'detail', text: 'engine step detail' }); + await writer.save(item); + await writer.saveLog([item], fixedDate); + assert.deepEqual([...writes.keys()], ['unpack/app.unpack.exe']); + assert.equal(file.saved, 'unpack/app.unpack.exe'); + assert.equal(item.log[0].text, 'engine step detail'); + assert.equal(state.notice.key, 'web.save_failed'); +}); + +test('folder writes keep allowed files and group refused names in one ZIP', async () => { + const writes = new Map(); + const root = directory(writes, { same: true }); + const writer = new FolderWriter(root); + const group = { kind: 'folder', name: 'source', handle: root, lastRun: { log: [] } }; + const exe = output('app.unpack.exe', 'exe bytes'); + const dll = output('lib/plugin.unpack.dll', 'first DLL'); + const another = output('lib/Plugin.unpack.DLL', 'second DLL'); + const input = record(group, exe, dll); + const entryParent = record(group); + const entry = { ...record(group, another), parent: entryParent }; + await writer.save(input); + await writer.save(entry); + assert.deepEqual([...writes.keys()], ['unpack/app.unpack.exe']); + assert.equal(await writes.get(exe.saved).text(), 'exe bytes'); + assert.equal(dll.refused, true); + await writer.finish(fixedDate); + const archive = 'unpack/senbei-remaining.20260102-030405-678.zip'; + assert.deepEqual([...writes.keys()], ['unpack/app.unpack.exe', archive]); + for (const item of [dll, another]) { + assert.equal(item.saved, archive); + assert.equal(item.saveFailed, null); + assert.equal(item.refused, false); + } + const zip = writes.get(archive); + const { entries } = await openZip(zip); + assert.deepEqual(entries.map((entry) => entry.name), ['lib/plugin.unpack.dll', 'lib/Plugin.unpack (2).DLL']); + for (const [i, expected] of ['first DLL', 'second DLL'].entries()) { + const recovered = await entryBlob(await entrySource(zip, entries[i]), 1024); + assert.equal(await recovered.text(), expected); + } + for (const owner of [input, entryParent, group.lastRun]) { + assert.equal(owner.log.length, 1); + assert.equal(owner.log[0].status, 'ok'); + } +}); + +test('a failed write after opening the file is not a name refusal', async () => { + const writes = new Map(); + const writer = new FolderWriter(directory(writes)); + const file = output('blocked.error', 'bytes'); + await writer.save(record({ kind: 'files' }, file)); + await writer.finish(fixedDate); + assert.equal(writes.size, 0); + assert.equal(file.saveFailed, 'unpack/blocked.error'); + assert.equal(file.refused, false); +}); + +test('if the folder refuses the fallback archive, the original stays downloadable', async () => { + const writes = new Map(); + const writer = new FolderWriter(directory(writes, { rejectZip: true })); + const file = output('plugin.unpack.dll', 'bytes'); + const item = record({ kind: 'files' }, file); + await writer.save(item); + await writer.finish(fixedDate); + assert.equal(writes.size, 0); + assert.equal(file.saved, null); + assert.equal(file.refused, true); + assert.match(file.saveFailed, /\.zip$/); + assert.equal(item.log[0].status, 'failed'); + assert.equal(await file.blob.text(), 'bytes'); +}); diff --git a/web/tests/page.test.js b/web/tests/page.test.js new file mode 100644 index 0000000..e833360 --- /dev/null +++ b/web/tests/page.test.js @@ -0,0 +1,473 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { test } from 'node:test'; + +import { LANGUAGES, loadLanguage, show, t, technical } from '../i18n.js'; +import { find, makeEntries, makeGroup, makeItem, state, targets } from '../state.js'; +import * as view from '../view.js'; +import { lineText } from '../detail.js'; +import { rowState, shownPath, typeTag } from '../ui.js'; +import { reportText } from '../text.js'; + +const web = new URL('..', import.meta.url); +const catalogs = Object.fromEntries( + await Promise.all( + LANGUAGES.map(async ([tag]) => [tag, (await import(new URL(`i18n/${tag}.js`, web))).default]), + ), +); + +/** Load the English catalog, as the page does before it draws anything. */ +async function english() { + globalThis.document ??= { documentElement: {} }; + await loadLanguage('en'); +} + +function reset() { + Object.assign(state, { + groups: [], + selected: null, + multi: [], + filter: 'all', + search: '', + tab: 'overview', + logLevel: 'all', + showNonTargets: false, + run: null, + saving: false, + scans: [], + out: { mode: 'downloads', dir: null }, + notice: null, + }); + state.collapsed.clear(); +} + +const candidate = (path) => ({ path, open: null }); + +/** The result of a job, as `run.js` records it. */ +function resultOf(info, outputs = []) { + return { + info: { warnings: [], errors: [], findings: [], routes: [], log: [], error: null, note: null, profile: null, metadata: null, elf: null, ...info }, + lang: 'en', + durationMs: 6, + retried: false, + companionUsed: false, + companionSize: null, + companionSha256: null, + inputSha256: null, + outputs: outputs.map((output) => ({ blob: null, size: 1, sha256: null, embedded: false, saved: null, saveFailed: null, refused: false, ...output })), + }; +} + +const profile = (extra = {}) => ({ + observed: { platform: 'windows_pe', format: 'pe32_plus', kind: 'native_dll' }, + evidence: ['signature'], + recognition: 'recognized', + static_validation: 'clean', + selected: 'dll', + ...extra, +}); + +test('the generated catalogs match the desktop wording they are taken from', () => { + execFileSync(process.execPath, [fileURLToPath(new URL('tools/gen-i18n.mjs', web)), '--check'], { + stdio: 'pipe', + }); +}); + +test('every language has the same keys and placeholders', () => { + const placeholders = (text) => [...text.matchAll(/\{(\w+)\}/g)].map((match) => match[1]).sort(); + const english = catalogs.en; + for (const [tag, catalog] of Object.entries(catalogs)) { + assert.deepEqual(Object.keys(catalog), Object.keys(english), tag); + for (const [key, text] of Object.entries(catalog)) { + assert.ok(text.length > 0, `${tag} ${key}`); + assert.deepEqual(placeholders(text), placeholders(english[key]), `${tag} ${key}`); + } + } +}); + +test('every key the page names is in the catalog', () => { + const source = ['app.js', 'run.js', 'output.js', 'state.js', 'view.js', 'detail.js', 'ui.js', 'report.js', 'text.js'] + .map((file) => readFileSync(new URL(file, web), 'utf8')) + .join('\n'); + const named = new Set(); + // t('key'), { key: 'key' }, pageError('key'), notify('key'), and key tables. + for (const match of source.matchAll(/'([A-Za-z]+\.[A-Za-z0-9_.]+)'/g)) named.add(match[1]); + for (const match of source.matchAll(/\bt\('([A-Za-z]+)'/g)) named.add(match[1]); + const missing = [...named].filter((key) => !(key in catalogs.en) && !key.startsWith('senbei.')); + assert.deepEqual(missing, []); + assert.ok(named.size > 120, String(named.size)); +}); + +test('messages follow the page language, engine messages only when it matches', () => { + // No catalog is loaded here, so `t` returns the key and the language is `en`. + assert.equal(t('missing.key'), 'missing.key'); + const engine = { text: 'English', local: '日本語' }; + assert.equal(show(engine), '日本語'); + assert.equal(technical(engine), 'English'); + assert.equal(show(engine, 'ja'), 'English'); + assert.equal(technical(engine, 'ja'), null); + assert.equal(show({ text: 'English', local: null }), 'English'); + assert.equal(technical({ text: 'English', local: null }), null); + const page = { key: 'web.over_limit', vars: { size: '1', limit: '2' }, text: 'x', tech: 'raw' }; + assert.equal(show(page, 'ja'), 'web.over_limit'); + assert.equal(technical(page), 'raw'); + // A message that names its own language is not bound to its job's. + assert.equal(show({ text: 'English', local: '日本語', lang: 'ja' }), 'English'); + assert.equal(show({ text: 'English', local: 'Local', lang: 'en' }, 'ja'), 'Local'); +}); + +test('a run covers the picked rows, else the selection, else every input', () => { + reset(); + const files = makeGroup('files', ''); + const folder = makeGroup('folder', 'game'); + const [a, b] = ['a.exe', 'b.dll'].map((path) => makeItem(files, candidate(path), 1)); + const pack = makeItem(folder, candidate('app.apk'), 1); + pack.kind = 'package'; + pack.container = { kind: 'apk', archives: [{ label: '', targets: [{ path: 'lib/x.so', entry: { size: 1 } }] }] }; + pack.entries = makeEntries(pack); + const lib = makeItem(folder, candidate('lib/y.so'), 1); + files.items.push(a, b); + folder.items.push(pack, lib); + state.groups = [files, folder]; + + assert.deepEqual(targets(), [a, b, pack, lib]); + state.selected = folder.id; + assert.deepEqual(targets(), [pack, lib]); + // An entry stands for its package. + state.selected = pack.entries[0].id; + assert.deepEqual(targets(), [pack]); + // Picked rows run in list order, and the shown row is not added to them. + state.multi = [lib.id, a.id]; + state.selected = b.id; + assert.deepEqual(targets(), [a, lib]); + assert.equal(find(pack.entries[0].id).item, pack.entries[0]); + assert.equal(find('nothing'), null); + reset(); +}); + +test('rows read as the workbench writes them', async () => { + await english(); + reset(); + const group = makeGroup('files', ''); + const make = (path, extra) => Object.assign(makeItem(group, candidate(path), 10), extra); + + const dll = make('bin/Plugin.dll', { kind: 'pe', pre: profile() }); + assert.equal(typeTag(dll), 'PE32+ DLL'); + assert.deepEqual(rowState(dll), { dot: null, label: 'Not run yet', tone: null, extra: null, time: null }); + dll.notProtected = true; + assert.equal(rowState(dll).label, 'Not protected'); + + dll.state = 'ok'; + dll.durationMs = 1420; + dll.result = resultOf({ status: 'recovered', profile: profile({ selected: 'exe_style' }) }); + assert.deepEqual(rowState(dll), { dot: 'ok', label: 'Recovered', tone: 'ok', extra: 'Unpacked', time: '1.42 s' }); + dll.state = 'running'; + assert.deepEqual(rowState(dll), { dot: 'info', label: 'Running…', tone: 'info', extra: null, time: null }); + dll.state = 'queued'; + assert.equal(rowState(dll).label, 'Queued'); + dll.state = 'cancelled'; + assert.equal(rowState(dll).label, 'Will not run'); + + assert.equal(typeTag(make('lib/libil2cpp.so', { kind: 'so' })), 'ELF64 AArch64'); + assert.equal(typeTag(make('global-metadata.dat', { kind: 'metadata', metadataVersion: 31 })), 'il2cpp metadata v31'); + assert.equal(typeTag(make('app.xapk', { kind: 'package', container: { kind: 'xapk' } })), 'XAPK'); + // A package that could not be listed, and a file that is no target. + assert.equal(typeTag(make('broken.apk', { kind: 'package' })), 'APK'); + assert.equal(typeTag(make('notes.txt', {})), 'TXT'); + assert.equal(typeTag(make('README', {})), '?'); +}); + +test('log lines read in the page language', async () => { + await english(); + const lines = [ + [{ type: 'run-started', n: 3 }, 'Unpack started · inputs: 3'], + [{ type: 'scan', n: 35, s: 35 }, 'Scan finished: candidates 35, non-targets skipped 35'], + [{ type: 'input-started', i: 2, n: 3, path: 'game/a.dll' }, 'Input 2/3: game/a.dll'], + [{ type: 'companion', name: 'a.dll._' }, 'Companion paired: a.dll._'], + [{ type: 'step', i: 1, of: 9, key: null, title: 'Custom step' }, 'Step 1/9: Custom step'], + [{ type: 'step', i: null, of: null, key: null, title: 'Alone' }, 'Alone'], + [{ type: 'detail', text: 'info[0] key = 0x1' }, 'info[0] key = 0x1'], + [{ type: 'stage', stage: 'recovery', status: 'ok', durationMs: 461, detail: null }, 'Recovery: OK (461 ms)'], + [{ type: 'stage', stage: 'detection', status: 'ok', durationMs: null, detail: null }, 'Detection: OK'], + [ + { type: 'stage', stage: 'recovery', status: 'failed', durationMs: 0, detail: { text: 'bad header', local: null }, lang: 'en' }, + 'Recovery: Failed — bad header', + ], + [{ type: 'message', message: { text: 'careful', local: null }, lang: 'en' }, 'careful'], + [{ type: 'entry', path: 'lib/x.so', outcome: 'entryStatus.restored' }, 'Entry lib/x.so: Restored'], + [{ type: 'finished', outcome: 'status.ok', durationMs: 1420 }, 'Finished: Recovered (1.42 s)'], + [{ type: 'summary', counts: { ok: 3, suspect: 0, failed: 1, skipped: 2 } }, '3 recovered · 0 suspect · 1 failed · 2 skipped'], + ]; + for (const [line, text] of lines) assert.equal(lineText(line), text); +}); + +test('the frame follows the selection and what has run', async () => { + await english(); + reset(); + assert.ok(view.detail().includes('Drop protected files here')); + const group = makeGroup('folder', 'game'); + const item = Object.assign(makeItem(group, candidate('bin/Plugin.dll'), 10), { kind: 'pe', pre: profile() }); + group.items.push(item); + state.groups = [group]; + + assert.ok(view.topbar().includes('>▶ Unpack all')); + assert.ok(view.detail().includes('Select an input or a group on the left.')); + // The filter chips wait for the first result. + assert.equal(view.chips(), ''); + assert.deepEqual(view.listRows().map((row) => row.key), [group.id, item.id]); + + state.selected = group.id; + assert.ok(view.topbar().includes('>▶ Unpack (1)')); + const pending = view.detail(); + for (const text of ['Summary', 'Folder scan', 'Non-targets skipped', 'Overview', 'Log']) assert.ok(pending.includes(text), text); + assert.ok(!pending.includes('Export JSON')); + + item.state = 'ok'; + item.durationMs = 6; + item.result = resultOf({ status: 'recovered', profile: profile() }, [{ path: 'bin/Plugin.unpack.dll' }]); + assert.ok(view.chips().includes('Recovered')); + assert.ok(view.detail().includes('Export text')); + state.selected = item.id; + const done = view.detail(); + for (const text of ['Recognition', 'Recovery routes', 'Stages', 'Identity', 'PE32+ DLL', shownPath('game/bin/Plugin.dll'), 'Unpacked · 6 ms']) { + assert.ok(done.includes(text), text); + } + state.filter = 'failed'; + assert.deepEqual(view.listRows().map((row) => row.key), ['none']); + reset(); +}); + +test('the folder picker explains the fallback before a folder is chosen', async () => { + await english(); + reset(); + state.settingsTab = 'general'; + const hint = view.esc(t('web.out_folder_help')); + for (const [lang, catalog] of Object.entries(catalogs)) { + assert.ok(catalog['web.out_folder_help'].includes('senbei-remaining.*.zip'), lang); + } + for (const [html, id] of [[view.outMenu(true), 'out-folder-help'], [view.settings(true), 'set-output-help']]) { + assert.ok(html.includes(`aria-describedby="${id}"`)); + assert.ok(html.includes(`id="${id}">${hint}

      `)); + } + for (const html of [view.outMenu(false), view.settings(false)]) { + assert.ok(!html.includes(hint)); + assert.ok(html.includes(view.esc(t('web.out_unsupported')))); + } + reset(); +}); + +test('the Overview and text export agree when a package has no targets', async () => { + await english(); + reset(); + const group = makeGroup('files', ''); + const item = Object.assign(makeItem(group, candidate('empty.apk'), 1), { + kind: 'package', + state: 'skipped', + container: { kind: 'apk', archives: [{ label: '', entryCount: 1, targets: [] }], problems: [] }, + entries: [], + }); + group.items.push(item); + state.groups = [group]; + state.selected = item.id; + assert.ok(view.detail().includes(t('pkg.no_targets'))); + assert.ok(reportText([item]).includes(t('pkg.no_targets'))); + assert.ok(!reportText([item]).includes(t('ov.no_routes'))); + reset(); +}); + +test('package inventory identifies which archive holds each candidate', async () => { + await english(); + reset(); + const group = makeGroup('files', ''); + const item = Object.assign(makeItem(group, candidate('app.xapk'), 2), { + kind: 'package', + state: 'ok', + container: { + kind: 'xapk', + archives: ['', 'split.apk'].map((label) => ({ + label, + targets: [{ path: 'lib/plugin.so', entry: { size: 1 } }], + })), + }, + }); + item.entries = makeEntries(item); + group.items.push(item); + state.groups = [group]; + state.selected = item.id; + state.tab = 'entries'; + for (const name of ['app.xapk', 'split.apk']) { + assert.ok(view.detail().includes(shownPath(`${name}::lib/plugin.so`))); + } + reset(); +}); + +test('names and messages from files are never markup', async () => { + await english(); + reset(); + const hostile = '"\'&'; + const message = { text: hostile, local: hostile }; + const group = makeGroup('folder', hostile); + const add = (path, extra) => { + const item = Object.assign(makeItem(group, candidate(path), 10), extra); + group.items.push(item); + return item; + }; + const outputs = [ + { path: hostile, sha256: hostile, saved: hostile }, + { path: hostile, sha256: hostile, embedded: true, saveFailed: hostile, refused: true }, + { path: hostile, saveFailed: hostile }, + ]; + const everyLine = [ + { type: 'run-started', n: hostile }, + { type: 'scan', n: hostile, s: hostile }, + { type: 'scan-incomplete' }, + { type: 'input-started', i: hostile, n: hostile, path: hostile }, + { type: 'companion', name: hostile }, + { type: 'step', i: 1, of: 2, key: null, title: hostile, lang: 'en' }, + { type: 'step', i: null, of: null, key: hostile, title: hostile, lang: 'en' }, + { type: 'detail', text: hostile }, + { type: 'stage', stage: hostile, status: hostile, durationMs: 5, detail: message, lang: 'en' }, + { type: 'message', message, lang: 'en' }, + { type: 'entry', path: hostile, outcome: hostile }, + { type: 'finished', outcome: hostile, durationMs: 5 }, + { type: 'summary', counts: { ok: hostile, suspect: hostile, failed: hostile, skipped: hostile } }, + { type: hostile, text: hostile }, + ].map((line, index) => ({ at: 1000 + index, level: ['info', 'step', 'detail', 'warn', 'error'][index % 5], ...line })); + + const hostileProfile = { + observed: { platform: hostile, format: hostile, kind: hostile, metadata_version: hostile }, + evidence: [hostile], + recognition: hostile, + static_validation: 'warnings', + selected: hostile, + }; + const info = { + profile: hostileProfile, + routes: [{ layout: hostile, outcome: hostile, errors: [{ text: `${hostile}2`, local: null }], warnings: [message] }], + warnings: [{ text: `${hostile}3`, local: null }], + errors: [{ text: `${hostile}4`, local: hostile }], + findings: [{ severity: 'fatal', message: `${hostile}5` }], + note: { text: `${hostile}6`, local: null }, + metadata: { version: hostile, remapped: hostile, identity: { raw_version: hostile, layout: hostile, capabilities: {} } }, + elf: { sections: hostile, segments: 1, dynamic_symbols: hostile, dynamic_relocations: 1, pltgot_relocations: hostile }, + }; + + const recovered = add(`${hostile}/${hostile}.dll`, { + kind: 'pe', + pre: hostileProfile, + state: 'suspect', + durationMs: 5, + companion: { state: 'unmatched', name: hostile }, + log: everyLine, + result: { ...resultOf({ ...info, status: 'recovered', suspect: true }, outputs), companionUsed: true, companionSize: 3, companionSha256: hostile, inputSha256: hostile }, + }); + const failed = add(`${hostile}.so`, { + kind: 'so', + state: 'failed', + durationMs: 5, + log: everyLine, + error: message, + result: resultOf({ ...info, status: 'failed', error: { text: `${hostile}7`, local: hostile } }), + }); + const skipped = add(`${hostile}.dat`, { + kind: 'metadata', + metadataVersion: hostile, + state: 'skipped', + log: everyLine, + result: resultOf({ ...info, status: 'unchanged' }), + }); + const unread = add(`${hostile}.apk`, { kind: 'package', entries: [], identityError: message }); + const pending = add(`${hostile}.exe`, { kind: 'pe', pre: hostileProfile, companion: { state: 'spliced', name: hostile } }); + const plain = add(hostile, { notProtected: true }); + const pendingPack = add(`${hostile}.xapk`, { kind: 'package' }); + const pack = add(`${hostile}.apks`, { kind: 'package', state: 'failed', durationMs: 5, log: everyLine, error: message }); + for (const item of [pendingPack, pack]) { + item.container = { + kind: hostile, + archives: [ + { + label: '', + entryCount: hostile, + identity: [hostile, hostile], + targets: [ + { path: `${hostile}/${hostile}.so`, entry: { size: 1 } }, + { path: `${hostile}/global-metadata.dat`, entry: { size: 2 } }, + ], + }, + { label: hostile, entryCount: 2, identity: null, targets: [{ path: `lib/${hostile}.so`, entry: { size: 3 } }] }, + ], + problems: [{ path: hostile, message: hostile }], + }; + item.entries = makeEntries(item); + } + const [restored, broken, other] = pack.entries; + Object.assign(restored, { state: 'ok', result: resultOf({ ...info, status: 'recovered' }, outputs) }); + Object.assign(broken, { state: 'failed', metadataVersion: hostile, error: message, result: resultOf({ ...info, status: 'failed' }) }); + Object.assign(other, { state: 'skipped', result: resultOf({ status: 'not_protected' }) }); + group.lastRun = { inputs: 3, index: 3, durationMs: 15, running: false, log: everyLine, finished: [] }; + group.stats = { skipped: 1, walkErrors: 2, probeErrors: 3 }; + state.groups = [group]; + state.out = { mode: 'folder', dir: { name: hostile } }; + state.notice = { key: 'web.saved', vars: { path: hostile }, tone: 'warn' }; + + const rendered = []; + const draw = () => { + for (const tab of ['overview', 'entries', 'log']) { + state.tab = tab; + rendered.push(view.detail()); + } + rendered.push(view.list(), view.topbar(), view.status(), view.chips()); + }; + const rows = [group, recovered, failed, skipped, unread, pending, plain, pendingPack, pack, ...pack.entries]; + for (const row of rows) { + state.selected = row.id; + state.multi = [recovered.id, row.id]; + state.showNonTargets = !state.showNonTargets; + draw(); + rendered.push(view.rowMenu(row.id, { kind: 'item', runnable: true, busy: false })); + } + // A scan in progress, then a run with one input in each state it can have. + group.scanning = true; + state.scans = [{ group }]; + state.selected = group.id; + draw(); + group.scanning = false; + state.scans = []; + recovered.state = 'running'; + failed.state = 'queued'; + skipped.state = 'cancelled'; + state.run = { + total: 3, + done: 1, + current: recovered, + step: { i: 1, of: 2, key: null, title: hostile }, + started: performance.now(), + stopping: true, + keep: recovered, + begun: new Set(), + groups: new Map(), + }; + group.lastRun.running = true; + for (const row of [group, recovered, failed, skipped]) { + state.selected = row.id; + draw(); + } + state.search = hostile; + draw(); + rendered.push(view.outMenu(true), view.outMenu(false), view.settings(true), view.legal(false), view.inputsFrame()); + + assert.ok(find(other.id)); + assert.ok(rendered.length > 60); + for (const html of rendered) { + const at = html.indexOf('"/.test(html)); + } + const all = rendered.join(''); + assert.ok(all.includes('<img src=x onerror=alert(1)>"'&')); + // The text report is plain text: the name is in it as it is. + assert.ok(reportText(group.items).includes(hostile)); + reset(); +}); diff --git a/web/tests/report.test.js b/web/tests/report.test.js index 89d74cb..8055192 100644 --- a/web/tests/report.test.js +++ b/web/tests/report.test.js @@ -1,504 +1,330 @@ -// 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 { test } from 'node:test'; 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, + closingLines, + companionLine, + engineLines, + fileReport, + fileStamp, + finishedLine, + messagePlan, + ranAsModule, reportFileName, serializeReport, - sortFindings, + stagesOf, } from '../report.js'; -const MiB = 1024 * 1024; -const file = (name, size) => ({ name, size }); +const message = (text, local = null) => ({ text, local }); -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', { +function recovered(overrides = {}) { + return { + name: 'Game.exe', + relPath: 'bin/Game.exe', + kind: 'pe', 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', + size: 1000, + pre: { recognition: 'recognized' }, + error: null, + result: { + info: { + status: 'recovered', + profile: { static_validation: 'clean', recognition: 'recognized' }, + error: null, + note: null, + warnings: [], + errors: [], + findings: [], + metadata: null, + elf: null, + log: [ + { ms: 1, step: 'Decrypt', i: 1, of: 2 }, + { ms: 2, detail: 'key=0x1' }, + { ms: 5, step: 'Rebuild', i: 2, of: 2 }, + ], + }, + durationMs: 12.6, + lang: 'en', + retried: false, + companionUsed: false, + inputSha256: 'aa', + outputs: [{ path: 'bin/Game.unpack.exe', size: 2000, sha256: 'bb', embedded: false, saved: null }], }, - }); - assert.equal(report.status, 'recovered'); - assert.equal(report.integrity.status, 'not_run'); - assert.equal(report.integrity.findings.length, 0); -}); + ...overrides, + }; +} -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"/); -}); +const stageList = (item) => stagesOf(item).map((stage) => [stage.stage, stage.status]); -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' }], +test('every message is shown once, where a reader looks for it', () => { + const item = recovered(); + item.result.info.warnings = [message('same'), message('other')]; + item.result.info.errors = [message('same')]; + // Why nothing was needed belongs to the recovery stage, not here. + item.result.info.note = message('note'); + const plan = messagePlan(item); + assert.deepEqual(plan.validation, []); + assert.deepEqual(plan.top.map((entry) => [entry.tone, entry.message.text]), [ + ['err', 'same'], + ['warn', 'other'], ]); - const report = buildReport(entries, { - generatedAt: '2026-11-05T12:34:56.789Z', - limitBytes: 64 * MiB, +}); + +test('static check findings go with the validation verdict', () => { + const item = recovered({ state: 'suspect' }); + const info = item.result.info; + info.profile.static_validation = 'warnings'; + info.findings = [ + { severity: 'warning', message: 'import table is empty' }, + { severity: 'fatal', message: 'entry point outside the image' }, + ]; + info.warnings = [message('import table is empty')]; + info.error = message('top level'); + const plan = messagePlan(item); + assert.deepEqual(plan.top.map((entry) => entry.message.text), ['top level']); + assert.deepEqual(plan.validation.map((entry) => [entry.tone, entry.message.text]), [ + ['warn', 'import table is empty'], + ['err', 'entry point outside the image'], + ]); +}); + +test('a page error is shown for an input with no result', () => { + const item = recovered({ state: 'failed', result: null, error: message('could not read') }); + assert.deepEqual(messagePlan(item).top, [{ tone: 'err', message: item.error }]); + assert.deepEqual(messagePlan(null), { top: [], validation: [] }); +}); + +test('a Windows module records every stage, a library and metadata what they have', () => { + const kept = ['output_write', 'skipped']; + const item = recovered(); + assert.deepEqual(stageList(item), [['detection', 'ok'], ['recovery', 'ok'], ['static_validation', 'ok'], kept]); + assert.equal(stagesOf(item)[1].durationMs, 13); + + item.result.info.suspect = true; + assert.deepEqual(stageList(item)[2], ['static_validation', 'failed']); + + const library = recovered({ kind: 'so' }); + assert.deepEqual(stageList(library), [['recovery', 'ok'], ['static_validation', 'ok'], kept]); + const metadata = recovered({ kind: 'metadata' }); + assert.deepEqual(stageList(metadata), [['recovery', 'ok'], kept]); +}); + +test('the job that ran decides what an input is taken for', () => { + // A library that turned out to be an ordinary one was told so as a module. + const library = recovered({ kind: 'so', state: 'failed' }); + library.result.op = 'pe'; + library.result.info.status = 'failed'; + library.result.info.error = message('not a protected file'); + assert.equal(ranAsModule(library), true); + assert.equal(stagesOf(library)[0].detail, library.result.info.error); + + assert.equal(ranAsModule(recovered()), true); + assert.equal(ranAsModule(recovered({ kind: null })), true); + assert.equal(ranAsModule(recovered({ kind: 'so' })), false); + assert.equal(ranAsModule(recovered({ kind: 'metadata' })), false); + assert.equal(ranAsModule(recovered({ kind: 'package' })), false); +}); + +test('an output is written only when a folder was chosen for it', () => { + const item = recovered(); + assert.deepEqual(stageList(item).at(-1), ['output_write', 'skipped']); + assert.equal(stagesOf(item).at(-1).detail, null); + + item.result.outputs[0].saved = 'unpack/bin/Game.unpack.exe'; + const written = stagesOf(item).at(-1); + assert.deepEqual([written.stage, written.status], ['output_write', 'ok']); + assert.deepEqual(written.detail, { text: 'unpack/bin/Game.unpack.exe', path: true }); + + // A successful write must not hide a refusal to write a second output. + item.result.outputs.push({ saveFailed: 'unpack/bin/Plugin.unpack.dll' }); + assert.deepEqual(stageList(item).at(-1), ['output_write', 'failed']); +}); + +test('an input that did not recover records the one stage that says why', () => { + const failed = recovered({ state: 'failed' }); + failed.result.info.status = 'failed'; + failed.result.info.error = message('not a protected file'); + assert.deepEqual(stagesOf(failed), [ + { stage: 'recovery', status: 'failed', durationMs: null, detail: failed.result.info.error }, + ]); + // A library's failure is in its messages, not in the stage. + const library = recovered({ kind: 'so', state: 'failed' }); + library.result.info.status = 'failed'; + library.result.info.error = message('bad segment'); + assert.equal(stagesOf(library)[0].detail, null); + + // A file run on its own says how long the look took; one of a folder, why + // it needed nothing. + const unchanged = recovered({ kind: 'metadata', state: 'skipped' }); + unchanged.result.info.status = 'unchanged'; + unchanged.result.info.note = message('already plain'); + unchanged.result.outputs = []; + assert.deepEqual(stagesOf(unchanged), [{ stage: 'recovery', status: 'skipped', durationMs: 13, detail: null }]); + unchanged.group = { kind: 'folder' }; + assert.deepEqual(stagesOf(unchanged), [ + { stage: 'recovery', status: 'skipped', durationMs: null, detail: unchanged.result.info.note }, + ]); + + const unread = recovered({ state: 'failed', result: null, error: message('could not read') }); + assert.deepEqual(stagesOf(unread), [ + { stage: 'recovery', status: 'failed', durationMs: null, detail: unread.error }, + ]); + assert.deepEqual(stagesOf(recovered({ state: 'pending', result: null })), []); + assert.deepEqual(stagesOf(recovered({ kind: 'package' })), []); + assert.deepEqual(stagesOf(null), []); +}); + +test('the engine lines keep their order and count time from the start of the job', () => { + const info = recovered().result.info; + info.log.push({ truncated: true }); + const lines = engineLines(info, 1000, 'ja'); + assert.deepEqual(lines.map((line) => [line.at, line.level, line.type]), [ + [1001, 'step', 'step'], + [1002, 'detail', 'detail'], + [1005, 'step', 'step'], + [1005, 'detail', 'detail'], + ]); + assert.deepEqual(lines[0], { at: 1001, level: 'step', type: 'step', i: 1, of: 2, key: null, title: 'Decrypt', lang: 'ja' }); + assert.equal(lines[1].text, 'key=0x1'); + assert.equal(lines[3].text, '…'); + assert.deepEqual(engineLines(null, 0, 'en'), []); +}); + +test('a log closes with the stages, the messages, the entries, and the outcome', () => { + const item = recovered({ durationMs: 12.6 }); + item.result.info.warnings = [message('careful', 'attention')]; + const lines = closingLines(item, 5000, { key: 'status.ok', tone: 'ok' }); + assert.deepEqual(lines.map((line) => [line.level, line.type]), [ + ['info', 'stage'], + ['info', 'stage'], + ['info', 'stage'], + ['info', 'stage'], + ['warn', 'message'], + ['info', 'finished'], + ]); + assert.ok(lines.every((line) => line.at === 5000)); + assert.equal(lines[1].stage, 'recovery'); + assert.equal(lines[1].lang, 'en'); + assert.equal(lines[3].stage, 'output_write'); + assert.equal(lines[4].message.local, 'attention'); + assert.deepEqual(lines[5], { at: 5000, level: 'info', type: 'finished', outcome: 'status.ok', durationMs: 12.6 }); + + const failed = recovered({ state: 'failed', result: null, error: message('could not read') }); + const closing = closingLines(failed, 1, { key: 'status.error', tone: 'err' }); + assert.deepEqual(closing.map((line) => [line.level, line.type]), [ + ['error', 'stage'], + ['error', 'message'], + ['error', 'finished'], + ]); + + const entries = [ + { path: 'lib/a.so', key: 'entryStatus.restored', tone: 'ok' }, + { path: 'lib/b.so', key: 'entryStatus.error', tone: 'err' }, + ]; + const packed = closingLines({ kind: 'package', durationMs: 7, result: null, error: null }, 2, { key: 'status.error', tone: 'err' }, entries); + assert.deepEqual(packed.map((line) => [line.level, line.type, line.path ?? null]), [ + ['info', 'entry', 'lib/a.so'], + ['error', 'entry', 'lib/b.so'], + ['error', 'finished', null], + ]); + assert.equal(packed[1].outcome, 'entryStatus.error'); +}); + +test('the lines of a group log name the outcome and the companion', () => { + const item = recovered(); + assert.deepEqual(finishedLine(item, 9, { key: 'status.suspect', tone: 'warn' }), { + at: 9, + level: 'warn', + type: 'finished', + outcome: 'status.suspect', + durationMs: 12.6, }); + assert.deepEqual(companionLine(item, 3), { at: 3, level: 'info', type: 'companion', name: 'Game.exe._' }); +}); + +test('a file report carries the engine profile verbatim', () => { + const item = recovered(); + const report = fileReport(item); + assert.equal(report.path, 'bin/Game.exe'); + assert.equal(report.status, 'ok'); + assert.deepEqual(report.input, { size: 1000, sha256: 'aa' }); + assert.equal(report.duration_ms, 13); + assert.equal(report.profile, item.result.info.profile); + assert.deepEqual(report.outputs, [ + { path: 'bin/Game.unpack.exe', size: 2000, sha256: 'bb', embedded_metadata: false }, + ]); + assert.equal(report.error, null); + assert.ok(!('container' in report)); + + const pending = fileReport(recovered({ state: 'pending', result: null })); + assert.deepEqual(pending.profile, { recognition: 'recognized' }); + assert.deepEqual(pending.outputs, []); + assert.equal(pending.duration_ms, null); + assert.equal(pending.input.sha256, null); +}); + +test('a package reports its archives and each entry', () => { + const entry = recovered({ name: 'libil2cpp.so', relPath: 'lib/arm64-v8a/libil2cpp.so', kind: 'so' }); + const item = { + name: 'app.xapk', + relPath: 'app.xapk', + kind: 'package', + state: 'ok', + size: 5000, + result: null, + error: null, + container: { + kind: 'xapk', + archives: [ + { label: '', entryCount: 3, targets: [], identity: null }, + { label: 'base.apk', entryCount: 40, targets: [{}, {}], identity: ['org.example.app', '12'] }, + ], + }, + entries: [entry], + }; + const report = fileReport(item); + assert.deepEqual(report.container, { + kind: 'xapk', + archives: [ + { path: null, entries: 3, candidates: 0, package: null, version: null }, + { path: 'base.apk', entries: 40, candidates: 2, package: 'org.example.app', version: '12' }, + ], + }); + assert.equal(report.entries.length, 1); + assert.equal(report.entries[0].path, 'lib/arm64-v8a/libil2cpp.so'); +}); + +test('the report counts inputs by state and serializes stably', () => { + const report = buildReport( + [recovered(), recovered({ state: 'failed', result: null, error: message('bad') }), recovered({ state: 'pending', result: null })], + { generatedAt: '2026-01-02T03:04:05.678Z', version: '9.9.9', limitBytes: 1024 }, + ); 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']); + assert.deepEqual(report.tool, { name: 'senbei-web', version: '9.9.9' }); + assert.deepEqual(report.summary, { inputs: 3, recovered: 1, suspect: 0, failed: 1, skipped: 0 }); + assert.equal(report.files[1].error, 'bad'); + const serialized = serializeReport(report); + assert.ok(serialized.endsWith('}\n')); + assert.deepEqual(JSON.parse(serialized), report); + // No bytes and no page objects leak into the report. + assert.ok(!serialized.includes('"blob"')); }); -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('report file names are safe and sortable', () => { + assert.equal(fileStamp('2026-01-02T03:04:05.678Z'), '20260102-030405'); + assert.equal(reportFileName('bin/My Game (1).exe', '2026-01-02T03:04:05Z'), 'My_Game_1_.exe.20260102-030405.report.json'); + assert.equal(reportFileName(null, '2026-01-02T03:04:05Z'), 'senbei.20260102-030405.report.json'); + assert.equal(reportFileName('...', null), 'senbei.report.json'); + assert.equal(reportFileName('a.exe', '2026-01-02T03:04:05Z', 'txt'), 'a.exe.20260102-030405.report.txt'); }); -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/); -}); - -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'); +test('an input that could not be examined reports why', () => { + const item = recovered({ state: 'pending', result: null, identityError: message('unsafe entry path') }); + assert.equal(fileReport(item).error, 'unsafe entry path'); + // A package's time is its own: it has no job of its own to time. + assert.equal(fileReport(recovered({ durationMs: 41.4 })).duration_ms, 41); }); diff --git a/web/tests/scan.test.js b/web/tests/scan.test.js new file mode 100644 index 0000000..fa9c95d --- /dev/null +++ b/web/tests/scan.test.js @@ -0,0 +1,209 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { collect, fileListRoot, walkEntry, walkFileList } from '../scan.js'; +import { UnsafeEntry, inventory } from '../package.js'; +import { entrySource } from '../zip.js'; +import { bytesOf, makeZip, text } from './archives.js'; + +// ---------- fakes for the browser's folder objects ---------- + +/** A dropped `FileSystemDirectoryEntry` that lists in batches of two. */ +function entryOf(name, tree, opened) { + const children = Object.entries(tree).map(([child, value]) => + typeof value === 'object' + ? entryOf(child, value, opened) + : { name: child, isDirectory: false, file: (done) => (opened.push(child), done({ name: child })) }, + ); + return { + name, + isDirectory: true, + createReader() { + let at = 0; + return { + readEntries(done, failed) { + if (tree.broken === 'unreadable') return failed(new Error('denied')); + const batch = children.slice(at, at + 2); + at += batch.length; + return done(batch); + }, + }; + }, + }; +} + +const TREE = { + 'Game.exe': 'file', + 'Game.exe._': 'file', + 'data.unity3d': 'file', + unpack: { 'Game.unpack.exe': 'file' }, + Game_Data: { + 'global-metadata.dat': 'file', + 'level0.assets': 'file', + Plugins: { 'steam.dll': 'file', Unpack: { 'steam.unpack.dll': 'file' } }, + }, + lib: { 'arm64-v8a': { 'libil2cpp.so': 'file' } }, + 'bundle.xapk': 'file', +}; + +// Path order, whatever order the browser listed the folder in. +const EXPECTED = [ + ['Game.exe', 'pe'], + ['Game_Data/Plugins/steam.dll', 'pe'], + ['Game_Data/global-metadata.dat', 'metadata'], + ['bundle.xapk', 'package'], + ['lib/arm64-v8a/libil2cpp.so', 'so'], +]; + +const found = (scan) => scan.candidates.map((candidate) => [candidate.path, candidate.kind]); + +test('a dropped directory entry is walked without opening a file, across batches', async () => { + const opened = []; + const scan = await collect(walkEntry(entryOf('game', TREE, opened))); + assert.deepEqual(found(scan), EXPECTED); + assert.deepEqual([...scan.companions.keys()], ['Game.exe._']); + assert.deepEqual(opened, []); + assert.deepEqual(await scan.candidates[0].open(), { name: 'Game.exe' }); + assert.deepEqual(opened, ['Game.exe']); + assert.deepEqual(await scan.companions.get('Game.exe._')(), { name: 'Game.exe._' }); +}); + +test('a folder input lists paths under the picked folder', async () => { + const files = [ + 'game/Game_Data/Plugins/steam.dll', + 'game/Game.exe', + 'game/Game.exe._', + 'game/unpack/Game.unpack.exe', + 'game/Game_Data/Plugins/Unpack/steam.unpack.dll', + 'game/readme.txt', + ].map((path) => ({ name: path.split('/').pop(), webkitRelativePath: path })); + assert.equal(fileListRoot(files), 'game'); + assert.equal(fileListRoot([]), ''); + const scan = await collect(walkFileList(files)); + assert.deepEqual(found(scan), [ + ['Game.exe', 'pe'], + ['Game_Data/Plugins/steam.dll', 'pe'], + ]); + assert.equal(await scan.candidates[1].open(), files[0]); +}); + +test('an unreadable directory is reported and the walk goes on', async () => { + const errors = []; + const tree = { a: { 'x.dll': 'file' }, b: { broken: 'unreadable' }, 'c.exe': 'file' }; + const scan = await collect(walkEntry(entryOf('game', tree, []), (error) => errors.push(error.message))); + assert.deepEqual(found(scan), [ + ['a/x.dll', 'pe'], + ['c.exe', 'pe'], + ]); + assert.deepEqual(errors, ['denied']); +}); + +test('a scan can be stopped', async () => { + const controller = new AbortController(); + controller.abort(); + const scan = await collect(walkEntry(entryOf('game', TREE, [])), controller.signal); + assert.deepEqual(scan.candidates, []); +}); + +// ---------- packages ---------- + +const identify = async (bytes, truncated) => (truncated ? null : text(bytes).split(':')); + +function apk(manifest, extra = []) { + return makeZip([ + { name: 'AndroidManifest.xml', data: manifest, deflate: true }, + { name: 'classes.dex', data: 'dex' }, + { name: 'lib/arm64-v8a/libil2cpp.so', data: 'library', deflate: true }, + { name: 'lib/arm64-v8a/libmain.so', data: 'main' }, + { name: 'assets/bin/Data/Managed/Metadata/global-metadata.dat', data: 'metadata' }, + { name: 'assets/data.unity3d', data: 'bulk' }, + ...extra, + ]); +} + +test('a package lists its manifest identity and only its targets', async () => { + const result = await inventory(apk('org.example.app:7'), 'dir/app.apk', identify); + assert.equal(result.kind, 'apk'); + assert.equal(result.archives.length, 1); + const [archive] = result.archives; + assert.equal(archive.label, ''); + assert.equal(archive.entryCount, 6); + assert.deepEqual(archive.identity, ['org.example.app', '7']); + assert.deepEqual(archive.targets.map((target) => target.path), [ + 'lib/arm64-v8a/libil2cpp.so', + 'lib/arm64-v8a/libmain.so', + 'assets/bin/Data/Managed/Metadata/global-metadata.dat', + ]); + assert.deepEqual(result.problems, []); +}); + +test('a package with an entry name that would leave it is refused whole', async () => { + for (const name of ['../evil.so', '/abs/evil.so', 'lib/../../notes.txt']) { + const blob = apk('org.example.app:7', [{ name, data: 'x' }]); + await assert.rejects(inventory(blob, 'app.apk', identify), UnsafeEntry, name); + } + // A package inside a bundle is held to the same rule. + const split = makeZip([{ name: '../escape.so', data: 'x' }]); + const bundle = makeZip([{ name: 'split.apk', data: await bytesOf(split) }]); + await assert.rejects(inventory(bundle, 'game.xapk', identify), UnsafeEntry); +}); + +test('repeated names and directory entries are not targets', async () => { + const blob = apk('org.example.app:7', [ + { name: 'lib/arm64-v8a/libmain.so', data: 'second' }, + { name: 'lib/arm64-v8a/', data: '' }, + { name: 'lib/./arm64-v8a/libil2cpp.so', data: 'same path, written another way' }, + ]); + const [archive] = (await inventory(blob, 'app.apk', identify)).archives; + assert.deepEqual(archive.targets.map((target) => target.path), [ + 'lib/arm64-v8a/libil2cpp.so', + 'lib/arm64-v8a/libmain.so', + 'assets/bin/Data/Managed/Metadata/global-metadata.dat', + ]); +}); + +test('a bundle is descended one level into its packages', async () => { + const base = apk('org.example.app:7'); + const split = makeZip([ + { name: 'AndroidManifest.xml', data: 'org.example.app:7' }, + { name: 'lib/arm64-v8a/libextra.so', data: 'extra' }, + { name: 'inner.apk', data: 'never opened' }, + ]); + const bundle = makeZip([ + { name: 'manifest.json', data: '{}' }, + { name: 'base.apk', data: await bytesOf(base) }, + { name: 'config.arm64_v8a.apk', data: await bytesOf(split), deflate: true }, + { name: 'broken.apk', data: 'not a zip at all, but long enough to look' }, + { name: 'lib/arm64-v8a/libtop.so', data: 'top' }, + ]); + const result = await inventory(bundle, 'game.XAPK', identify); + assert.equal(result.kind, 'xapk'); + assert.deepEqual(result.archives.map((archive) => archive.label), ['', 'base.apk', 'config.arm64_v8a.apk']); + assert.equal(result.archives[0].identity, null); + assert.deepEqual(result.archives[0].targets.map((target) => target.path), ['lib/arm64-v8a/libtop.so']); + assert.deepEqual(result.archives[1].identity, ['org.example.app', '7']); + assert.deepEqual(result.archives[2].targets.map((target) => target.path), ['lib/arm64-v8a/libextra.so']); + assert.deepEqual(result.problems.map((problem) => problem.path), ['broken.apk']); + + // A target is read through its own archive, also when that one was stored. + const [target] = result.archives[1].targets; + const source = await entrySource(result.archives[1].blob, target.entry); + assert.equal(source.size, 'library'.length); +}); + +test('a nested package over the limit is a problem, not a read', async () => { + const split = makeZip([{ name: 'lib/arm64-v8a/libextra.so', data: 'extra'.repeat(100) }]); + const bundle = makeZip([{ name: 'split.apk', data: await bytesOf(split), deflate: true }]); + const result = await inventory(bundle, 'game.apks', identify, { maxNestedBytes: 10 }); + assert.equal(result.archives.length, 1); + assert.equal(result.problems.length, 1); +}); + +test('a manifest that cannot be read leaves the package unnamed', async () => { + const failing = async () => { + throw new Error('bad manifest'); + }; + const [archive] = (await inventory(apk('x:y'), 'app.apk', failing)).archives; + assert.equal(archive.identity, null); + assert.equal(archive.targets.length, 3); +}); diff --git a/web/tests/zip.test.js b/web/tests/zip.test.js new file mode 100644 index 0000000..ebe8010 --- /dev/null +++ b/web/tests/zip.test.js @@ -0,0 +1,137 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { + ZipError, + buildZip, + crc32, + entryBlob, + entrySource, + openZip, + readEntryPrefix, +} from '../zip.js'; +import { bytesOf, makeZip, text } from './archives.js'; + +test('crc32 matches the standard check value and continues across chunks', () => { + const bytes = new TextEncoder().encode('123456789'); + assert.equal(crc32(bytes), 0xcbf43926); + assert.equal(crc32(bytes.subarray(4), crc32(bytes.subarray(0, 4))), 0xcbf43926); +}); + +test('a built archive reads back with the same names and bytes', async () => { + const files = [ + { path: 'lib/arm64-v8a/libil2cpp.unpack.so', blob: new Blob(['library']) }, + { path: '日本語/メタ.dat', blob: new Blob([new Uint8Array([0, 1, 2, 255])]) }, + { path: 'empty.bin', blob: new Blob([]) }, + ]; + const archive = await buildZip(files, new Date(2026, 0, 2, 3, 4, 6)); + assert.equal(archive.type, 'application/zip'); + const { entries } = await openZip(archive); + assert.deepEqual(entries.map((entry) => entry.name), files.map((file) => file.path)); + for (const [index, entry] of entries.entries()) { + assert.equal(entry.method, 0); + const source = await entrySource(archive, entry); + const blob = await entryBlob(source, 1 << 20); + assert.deepEqual(await bytesOf(blob), await bytesOf(files[index].blob)); + } +}); + +test('a deflated entry is inflated and checked', async () => { + const body = 'senbei '.repeat(2000); + const archive = makeZip([{ name: 'a.txt', data: body, deflate: true }]); + const { entries } = await openZip(archive); + assert.equal(entries[0].method, 8); + assert.ok(entries[0].compressedSize < entries[0].size); + const source = await entrySource(archive, entries[0]); + assert.equal(text(await bytesOf(await entryBlob(source, 1 << 20))), body); + const prefix = await readEntryPrefix(source, 10); + assert.equal(text(prefix.bytes), body.slice(0, 10)); + assert.equal(prefix.truncated, true); + const whole = await readEntryPrefix(source, 1 << 20); + assert.equal(whole.bytes.length, body.length); + assert.equal(whole.truncated, false); +}); + +test('an entry that does not match its checksum or size is refused', async () => { + const wrongCrc = makeZip([{ name: 'a', data: 'abcdef', deflate: true, crc: 1 }]); + let source = await entrySource(wrongCrc, (await openZip(wrongCrc)).entries[0]); + await assert.rejects(entryBlob(source, 1 << 20), /checksum/); + + // The directory declares fewer bytes than the entry inflates to. + const longer = makeZip([{ name: 'a', data: 'abcdef'.repeat(100), deflate: true, size: 10 }]); + source = await entrySource(longer, (await openZip(longer)).entries[0]); + await assert.rejects(entryBlob(source, 1 << 20), /longer than its declared size/); + // A bounded read never takes more than the declared size either. + assert.equal((await readEntryPrefix(source, 1 << 20)).bytes.length, 10); + + const over = makeZip([{ name: 'a', data: 'abcdef' }]); + source = await entrySource(over, (await openZip(over)).entries[0]); + await assert.rejects(entryBlob(source, 3), /over the 3-byte limit/); +}); + +test('encrypted entries and unknown compression are refused', async () => { + const locked = makeZip([{ name: 'a', data: 'abc', encrypted: true }]); + const [entry] = (await openZip(locked)).entries; + assert.equal(entry.encrypted, true); + await assert.rejects(entrySource(locked, entry), ZipError); + await assert.rejects(entrySource(locked, { ...entry, encrypted: false, method: 12 }), /unsupported compression/); +}); + +test('an entry that points outside the file is refused', async () => { + const archive = makeZip([{ name: 'a', data: 'abc' }]); + const [entry] = (await openZip(archive)).entries; + await assert.rejects(entrySource(archive, { ...entry, headerOffset: archive.size }), ZipError); + await assert.rejects( + entrySource(archive, { ...entry, compressedSize: 1 << 20, size: 1 << 20 }), + /outside the file/, + ); +}); + +test('a file that is not an archive, or declares too much, is refused', async () => { + await assert.rejects(openZip(new Blob(['short'])), ZipError); + await assert.rejects(openZip(new Blob([new Uint8Array(100)])), /end-of-directory/); + const archive = makeZip([ + { name: 'a', data: '1' }, + { name: 'b', data: '2' }, + ]); + await assert.rejects(openZip(archive, { maxEntries: 1 }), /over the limit/); + await assert.rejects(openZip(archive, { maxDirectoryBytes: 10 }), /over the limit/); + // An entry count the directory cannot hold. + const bytes = await bytesOf(archive); + new DataView(bytes.buffer).setUint16(bytes.length - 22 + 10, 500, true); + await assert.rejects(openZip(new Blob([bytes])), /shorter than its entry count/); +}); + +test('ZIP64 directory records are followed', async () => { + const archive = makeZip([{ name: 'big.bin', data: 'payload' }]); + const bytes = await bytesOf(archive); + const end = bytes.length - 22; + const view = new DataView(bytes.buffer); + const directorySize = view.getUint32(end + 12, true); + const directoryOffset = view.getUint32(end + 16, true); + + const record = new DataView(new ArrayBuffer(56)); + record.setUint32(0, 0x06064b50, true); + record.setBigUint64(4, 44n, true); + record.setBigUint64(24, 1n, true); + record.setBigUint64(32, 1n, true); + record.setBigUint64(40, BigInt(directorySize), true); + record.setBigUint64(48, BigInt(directoryOffset), true); + const locator = new DataView(new ArrayBuffer(20)); + locator.setUint32(0, 0x07064b50, true); + locator.setBigUint64(8, BigInt(end), true); + locator.setUint32(16, 1, true); + const tail = bytes.slice(end); + const tailView = new DataView(tail.buffer); + tailView.setUint16(8, 0xffff, true); + tailView.setUint16(10, 0xffff, true); + tailView.setUint32(12, 0xffffffff, true); + tailView.setUint32(16, 0xffffffff, true); + + const zip64 = new Blob([bytes.subarray(0, end), record.buffer, locator.buffer, tail]); + const { entries } = await openZip(zip64); + assert.equal(entries.length, 1); + assert.equal(entries[0].name, 'big.bin'); + const source = await entrySource(zip64, entries[0]); + assert.equal(text(await bytesOf(await entryBlob(source, 100))), 'payload'); +}); diff --git a/web/text.js b/web/text.js new file mode 100644 index 0000000..096c936 --- /dev/null +++ b/web/text.js @@ -0,0 +1,96 @@ +// The text form of a report: what the overview and the log of each input say, +// as plain lines in the page language. Loaded when a text export is asked for. + +import { show, t, tv } from './i18n.js'; +import { fullPath, isDone, outcomeOf, targetEntries } from './state.js'; +import { baseName, formatBytes, formatDuration, localClock } from './model.js'; +import { messagePlan, stagesOf } from './report.js'; +import { lineText } from './detail.js'; +import { formatLabel, routeOf, rowState, shownPath, typeTag } from './ui.js'; + +const LEVEL = { info: 'log.lv_info', step: 'log.lv_step', warn: 'log.lv_warn', error: 'log.lv_error' }; +const MARK = { err: '✕', warn: '!', info: 'i' }; + +const sized = (size, sha256) => (sha256 ? `${formatBytes(size)} · SHA-256 ${sha256}` : formatBytes(size)); + +/** The lines for the outputs of an input or entry, at `depth`. */ +function outputLines(add, depth, source) { + for (const output of source.result?.outputs ?? []) { + add(depth, `${t('ov.output')}: ${shownPath(output.path)} · ${sized(output.size, output.sha256)}`); + } +} + +function recoveryLines(add, item) { + const result = item.result; + const info = result?.info; + const profile = info?.profile; + if (profile) { + const observed = profile.observed ?? {}; + add(1, `${t('ov.recognition')}: ${tv('recognition', profile.recognition)}`); + if (observed.platform) add(2, `${t('ov.platform')}: ${tv('platform', observed.platform)}`); + if (observed.format) add(2, `${t('ov.format')}: ${formatLabel(observed.format)}`); + if (observed.kind) add(2, `${t('ov.kind')}: ${tv('kind', observed.kind)}`); + const evidence = (profile.evidence ?? []).map((name) => tv('evidence', name)); + add(2, `${t('ov.evidence')}: ${evidence.length ? evidence.join(', ') : t('ov.no_evidence')}`); + } + const routes = info?.routes ?? []; + add(1, `${t('ov.routes')}:${routes.length ? '' : ` ${t('ov.no_routes')}`}`); + for (const route of routes) { + const selected = route.layout === profile?.selected ? ` ★ ${t('ov.selected')}` : ''; + add(2, `${tv('layout', route.layout)}: ${tv('outcome', route.outcome)}${selected}`); + for (const message of [...(route.errors ?? []), ...(route.warnings ?? [])]) add(3, show(message, result.lang)); + } + const stages = stagesOf(item).map((stage) => { + const time = stage.durationMs > 0 ? ` (${formatDuration(stage.durationMs)})` : ''; + return `${tv('stage', stage.stage)}: ${tv('stageStatus', stage.status)}${time}`; + }); + if (stages.length) add(1, `${t('ov.stages')}: ${stages.join(' → ')}`); + if (profile) add(1, `${t('ov.validation')}: ${tv('validation', profile.static_validation)}`); + if (info?.status !== 'recovered') return; + add(1, `${t('ov.source')}: ${sized(item.size, result.inputSha256)}`); + if (result.companionUsed) { + const size = result.companionSize == null ? '' : ` · ${sized(result.companionSize, result.companionSha256)}`; + add(1, `${t('ov.companion')}: ${tv('companion', 'spliced')} · ${baseName(item.relPath)}._${size}`); + } + outputLines(add, 1, item); +} + +function inputLines(item) { + const lines = []; + const add = (depth, text) => lines.push(`${' '.repeat(depth)}${text}`); + const row = rowState(item); + add(0, shownPath(fullPath(item))); + add(1, [row.label, row.extra, row.time].filter(Boolean).join(' · ')); + add(1, `${t('col.type')}: ${typeTag(item)}`); + if (item.identityError) add(1, `${MARK.err} ${show(item.identityError)}`); + if (!isDone(item)) return lines; + + const plan = messagePlan(item); + for (const { tone, message } of [...plan.top, ...plan.validation]) { + add(1, `${MARK[tone] ?? MARK.info} ${show(message, item.result?.lang)}`); + } + if (item.kind === 'package' && item.container) { + const entries = targetEntries(item); + if (!entries.length) add(1, t('pkg.no_targets')); + for (const entry of entries) { + const route = routeOf(entry); + add(1, `${shownPath(entry.target.path)}: ${t(outcomeOf(entry).key)}${route ? ` · ${route}` : ''}`); + outputLines(add, 2, entry); + } + } else { + recoveryLines(add, item); + } + if (item.log?.length) { + add(1, `${t('tab.log')}:`); + for (const line of item.log) { + const level = LEVEL[line.level] ? t(LEVEL[line.level]) : ''; + add(2, `${localClock(line.at)} ${level.padEnd(6)} ${lineText(line)}`); + } + } + return lines; +} + +/** The text report for `items`, one block for each input. */ +export function reportText(items) { + return `${items.map((item) => inputLines(item).join('\n')).join('\n\n')}\n`; +} diff --git a/web/tools/gen-i18n.mjs b/web/tools/gen-i18n.mjs new file mode 100644 index 0000000..96790af --- /dev/null +++ b/web/tools/gen-i18n.mjs @@ -0,0 +1,183 @@ +// Generate the page's language catalogs. +// +// node web/tools/gen-i18n.mjs write web/i18n/.js +// node web/tools/gen-i18n.mjs --check exit 1 when a written file is stale +// +// The desktop GUI's catalogs (`senbei-gui/src/text/.rs`) hold the +// approved wording, and the page shows the same workbench, so its text is +// taken from them and never retyped. Only the entries the page uses are +// copied: the research, hex, and compare views are not in the browser. Wording +// that exists only in the browser is in `web/i18n/web-strings.json`. +// +// An entry that takes no arguments is named by its catalog key +// (`tb.add_files`). An entry with arguments has no key in the Rust catalog and +// is named by its variant (`TbUnpackN`); its `{n}` placeholders are kept. + +import { readFileSync, writeFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; + +const webDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const textDir = path.resolve(webDir, '../senbei-gui/src/text'); + +/** Page language tag, and the Rust module holding it. */ +export const LANGUAGES = [ + ['en', 'en'], + ['zh-CN', 'zh_cn'], + ['zh-TW', 'zh_tw'], + ['ja', 'ja'], + ['ko', 'ko'], +]; + +/** Catalog keys the page uses. A trailing `.` takes every key under it. */ +const KEYS = [ + 'tb.add_files', 'tb.add_folder', 'tb.unpack', 'tb.unpack.all', 'tb.output', 'tb.settings', + 'empty.', 'drag.title', 'inputs.', 'filter.', 'group.files', 'mode.unpack', + 'menu.copy_path', 'menu.remove', + 'pending.not_run', 'pending.not_protected', 'pending.identified', 'pending.next', + 'pending.not_protected_note', + 'scan.', 'run.', 'step.', + 'detail.pick', 'detail.export_json', 'detail.export_text', 'detail.copy', 'detail.technical', + 'companion.', 'tab.overview', 'tab.entries', 'tab.log', 'batch.', 'pkg.', + 'entries.title', 'entries.remapped_label', + 'col.name', 'col.type', 'col.outcome', 'col.route', 'col.time', 'col.status', 'col.source', + 'common.', 'ov.', 'log.', 'status.', + 'legal.title', 'legal.p1', 'legal.p2', 'legal.p3', 'legal.p4', 'legal.accept', + 'settings.title', 'settings.tab_general', 'settings.tab_memory', 'settings.tab_about', + 'settings.language', 'settings.output', 'settings.output_recent', 'settings.output_choose', + 'settings.reset', 'settings.done', 'about.', + 'entryStatus.restored', 'entryStatus.not_target', 'entryStatus.unchanged', 'entryStatus.error', + 'entryKind.', 'recognition.', 'outcome.', 'validation.', + 'stage.detection', 'stage.recovery', 'stage.static_validation', 'stage.output_write', + 'stageStatus.', 'metaLayout.', + 'evidence.', 'platform.', 'kind.', 'kindShort.', 'layout.', +]; + +/** Keys under a prefix above that belong to views the page does not have. */ +const NOT_SHOWN = ['ov.provenance', 'ov.open_folder', 'status.recognized']; + +/** Entries with arguments the page uses, by variant name. */ +const VARIANTS = [ + 'TbUnpackN', 'GroupScanning', 'ScanStatus', 'RunStep', 'DetailLastRun', + 'PkgInventory', 'EntriesOthers', 'EntriesSummary', 'EntriesShowNonTargets', 'EntriesRemapped', + 'LogRunStarted', 'LogScan', 'LogInputStarted', 'LogCompanion', 'LogStep', 'LogEntry', + 'LogInputFinished', 'LogSummary', + 'AboutVersion', 'TagMetadata', +]; + +/** The value of a Rust string literal body (the text between the quotes). */ +function unescape(body, formatted) { + let out = ''; + for (let i = 0; i < body.length; i += 1) { + const ch = body[i]; + if (ch === '\\') { + const next = body[i + 1]; + i += 1; + if (next === 'n') out += '\n'; + else if (next === 't') out += '\t'; + else if (next === '"' || next === '\\' || next === "'") out += next; + else if (next === 'u') { + const close = body.indexOf('}', i); + out += String.fromCodePoint(parseInt(body.slice(i + 2, close), 16)); + i = close; + } else throw new Error(`unsupported escape \\${next}`); + } else if (formatted && (ch === '{' || ch === '}') && body[i + 1] === ch) { + // `{{` and `}}` are literal braces in a format string. + out += ch; + i += 1; + } else { + out += ch; + } + } + return out; +} + +/** Variant name to catalog key, for the entries that have one. */ +function catalogKeys() { + const source = readFileSync(path.join(textDir, 'catalog.rs'), 'utf8'); + const keys = new Map(); + for (const match of source.matchAll(/^\s*"([^"]+)" => Text::(\w+),$/gm)) { + keys.set(match[2], match[1]); + } + return keys; +} + +/** Variant name to `{ text, formatted }` for one language. */ +function catalogText(module) { + const source = readFileSync(path.join(textDir, `${module}.rs`), 'utf8'); + const arm = /^\s*Text::(\w+)(?: \{[^}]*\})? => (format!\()?"((?:[^"\\]|\\.)*)"\)?\.into\(\),$/gm; + const text = new Map(); + for (const match of source.matchAll(arm)) { + const formatted = match[2] !== undefined; + text.set(match[1], unescape(match[3], formatted)); + } + return text; +} + +function wanted(key) { + if (NOT_SHOWN.includes(key)) return false; + return KEYS.some((entry) => (entry.endsWith('.') ? key.startsWith(entry) : key === entry)); +} + +/** The catalog module source for one language. */ +export function generate(tag, module) { + const keys = catalogKeys(); + const text = catalogText(module); + const catalog = {}; + for (const [variant, key] of keys) { + if (!wanted(key)) continue; + if (!text.has(variant)) throw new Error(`${module}.rs has no text for ${variant}`); + catalog[key] = text.get(variant); + } + for (const entry of KEYS) { + const found = Object.keys(catalog).some((key) => + entry.endsWith('.') ? key.startsWith(entry) : key === entry); + if (!found) throw new Error(`no catalog key matches ${entry}`); + } + for (const variant of VARIANTS) { + if (!text.has(variant)) throw new Error(`${module}.rs has no text for ${variant}`); + catalog[variant] = text.get(variant); + } + const web = JSON.parse(readFileSync(path.join(webDir, 'i18n/web-strings.json'), 'utf8')); + for (const [key, languages] of Object.entries(web)) { + if (typeof languages[tag] !== 'string') throw new Error(`${key} has no ${tag} text`); + catalog[key] = languages[tag]; + } + const lines = Object.entries(catalog).map( + ([key, value]) => ` ${JSON.stringify(key)}: ${JSON.stringify(value)},`, + ); + return [ + '// Generated by web/tools/gen-i18n.mjs from senbei-gui/src/text and', + '// web/i18n/web-strings.json. Edit the wording there and run the generator.', + 'export default {', + ...lines, + '};', + '', + ].join('\n'); +} + +function main() { + const check = process.argv.includes('--check'); + let stale = false; + for (const [tag, module] of LANGUAGES) { + const file = path.join(webDir, 'i18n', `${tag}.js`); + const source = generate(tag, module); + if (!check) { + writeFileSync(file, source); + continue; + } + let current = null; + try { + current = readFileSync(file, 'utf8'); + } catch { + // A missing file is stale. + } + if (current !== source) { + console.error(`${path.relative(process.cwd(), file)} is stale; run web/tools/gen-i18n.mjs`); + stale = true; + } + } + if (stale) process.exit(1); +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main(); diff --git a/web/tools/stage.mjs b/web/tools/stage.mjs new file mode 100644 index 0000000..910d7eb --- /dev/null +++ b/web/tools/stage.mjs @@ -0,0 +1,46 @@ +// Stage the static site: the files the page loads, and nothing else. +// +// node web/tools/stage.mjs +// +// Run after `wasm-pack build --target web --out-dir ../web/pkg`. The CI +// artifact and the release deployment are both made from this directory, so +// the list of what ships is here once. + +import { cpSync, existsSync, mkdirSync, readdirSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; + +const web = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + +/** Paths under `web/` that make up the site. */ +export function siteFiles() { + const top = readdirSync(web).filter( + (name) => name.endsWith('.js') || ['index.html', 'style.css', 'LICENSE'].includes(name), + ); + const catalogs = readdirSync(path.join(web, 'i18n')) + .filter((name) => name.endsWith('.js')) + .map((name) => `i18n/${name}`); + const assets = readdirSync(path.join(web, 'assets')).map((name) => `assets/${name}`); + const engine = ['pkg/senbei_wasm.js', 'pkg/senbei_wasm_bg.wasm']; + return [...top, ...catalogs, ...assets, ...engine].sort(); +} + +function main() { + const dist = process.argv[2]; + if (!dist) { + console.error('usage: stage.mjs '); + process.exit(2); + } + for (const file of siteFiles()) { + const from = path.join(web, file); + if (!existsSync(from)) { + console.error(`${file} is missing; build senbei-wasm into web/pkg first`); + process.exit(1); + } + const to = path.join(dist, file); + mkdirSync(path.dirname(to), { recursive: true }); + cpSync(from, to); + } +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main(); diff --git a/web/ui.js b/web/ui.js new file mode 100644 index 0000000..b8ebeac --- /dev/null +++ b/web/ui.js @@ -0,0 +1,238 @@ +// Small pieces every view is built from, and how an input is labelled. + +import { show, t, technical, tv } from './i18n.js'; +import { isNonTarget, outcomeOf, state, timeOf } from './state.js'; +import { formatDuration, shortHash } from './model.js'; + +const ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; + +/** `value` as text that is safe inside an element or a quoted attribute. */ +export const esc = (value) => String(value ?? '').replace(/[&<>"']/g, (ch) => ESCAPES[ch]); + +export const pill = (tone, text) => `${esc(text)}`; +export const tag = (text) => `${esc(text)}`; +export const note = (text) => `

      ${esc(text)}

      `; +export const dim = (text) => `${esc(text)}`; +export const faint = (text) => `${esc(text)}`; +export const mono = (text) => `${esc(text)}`; + +/** A status dot; no tone draws a hollow one. */ +export const dot = (tone) => ``; + +/** + * A two-column list. Each row is `[label, html]`; falsy rows are left out. + * `sized` holds labels the label column is wide enough for although they are + * not shown, so that the column is the same in every view of one kind. + */ +export function kv(rows, sized = []) { + // The labels that only take up room sit, without height, in the first one. + const room = sized.map((label) => ``).join(''); + const cells = rows + .filter(Boolean) + .map(([key, value], index) => `
      ${esc(key)}${index === 0 ? room : ''}
      ${value}
      `); + return `
      ${cells.join('')}
      `; +} + +/** A card. `title` may be `null`; `aside` is HTML at the right of the title. */ +export function card(title, body, options = {}) { + const aside = options.aside ? `${options.aside}` : ''; + const head = title === null ? '' : `

      ${esc(title)}${aside}

      `; + return `
      ${head}${body}
      `; +} + +/** + * A two-column grid of cards. A card left alone in its row takes the row, so + * the grid has no empty half. + */ +export function grid(cards) { + const wide = (html) => html.startsWith('
      ${out.join('')}` : ''; +} + +/** Text with `` `code` `` spans set in monospace, as engine messages write names. */ +export function codeSpans(text) { + const parts = String(text ?? '').split('`'); + if (parts.length < 3) return esc(text); + return parts + .map((part, index) => (index % 2 === 1 ? `${esc(part)}` : esc(part))) + .join(''); +} + +const MESSAGE_ICON = { err: '✕', warn: '!', info: 'i' }; + +/** + * A part that is folded until its header is clicked. `key` names it, so that + * it stays as it was left when the view is drawn again; `summary` and `body` + * are HTML. + */ +export const fold = (kind, key, summary, body) => + `
      ` + + `${summary}${body}
      `; + +/** + * Message blocks for a list of `{ tone, message }`. `lang` is the language the + * messages' job ran in. `quiet` shows every block as plain information. + */ +export function messages(plan, lang, quiet = false) { + const rows = plan.map(({ tone, message }) => { + const kind = quiet ? 'info' : tone; + const more = technical(message, lang); + const detail = more + ? fold('tech', `tech:${more}`, esc(t('detail.technical')), `
      ${esc(more)}
      `) + : ''; + return ( + `
      ${MESSAGE_ICON[kind] ?? 'i'}` + + `
      ${codeSpans(show(message, lang))}
      ${detail}
      ` + ); + }); + return `
      ${rows.join('')}
      `; +} + +/** A hash, shortened, with the whole of it as the tooltip and a copy button. */ +export function hash(sha256) { + if (!sha256) return ''; + return ( + `${esc(shortHash(sha256))}` + + `` + ); +} + +const WINDOWS = /win/i.test(globalThis.navigator?.userAgentData?.platform ?? globalThis.navigator?.platform ?? ''); + +/** A path as this system writes it: with backslashes on Windows. */ +export const shownPath = (path) => (WINDOWS ? String(path ?? '').replace(/\//g, '\\') : String(path ?? '')); + +// ---------- labels ---------- + +/** A group's title: the folder's name, or the name of the loose-files group. */ +export const groupName = (group) => (group.kind === 'files' ? t('group.files') : group.name); + +/** What a run is called once it has finished: the page only unpacks. */ +export const modeLabel = () => t('mode.unpack'); + +/** + * A step's title in the page language. A step the catalog names is worded by + * the catalog; any other keeps the title its job gave it. + */ +export function stepTitle(step) { + if (!step?.key) return step?.title ?? ''; + const key = `step.${step.key}`; + const text = t(key); + return text === key ? step.title : text; +} + +/** A step with its position, as the status bar and the progress card show it. */ +export function stepText(step) { + if (!step) return ''; + const title = stepTitle(step); + return step.i == null ? title : t('RunStep', { i: step.i, n: step.of, s: title }); +} + +const FORMATS = { pe32: 'PE32', pe32_plus: 'PE32+', elf64_aarch64: 'ELF64 AArch64' }; + +/** A binary format as the workbench writes it. */ +export const formatLabel = (format) => FORMATS[format] ?? (format ? String(format).replace(/_/g, ' ') : '—'); + +function extensionTag(name) { + const dot = name.lastIndexOf('.'); + return dot < 0 ? '?' : name.slice(dot + 1).toUpperCase(); +} + +const metadataTag = (version) => t('TagMetadata', { v: version ?? '?' }); + +/** The tag an observed target gives, when it names a format or a version. */ +function observedTag(observed, version) { + if (!observed) return null; + if (observed.platform === 'il2cpp_metadata') return metadataTag(observed.metadata_version ?? version); + if (!observed.format) return null; + const format = formatLabel(observed.format); + return observed.kind ? `${format} ${tv('kindShort', observed.kind)}` : format; +} + +/** The tag an input had when it was added, from what its first bytes said. */ +function identityTag(item) { + switch (item.kind) { + case 'metadata': + return metadataTag(item.metadataVersion); + case 'so': + return FORMATS.elf64_aarch64; + case 'package': + return item.container ? item.container.kind.toUpperCase() : null; + default: + return observedTag(item.pre?.observed); + } +} + +/** + * The short type of an input or entry, as its row's tag. A run that failed + * before it read the format keeps the tag the file had when it was added. + */ +export function typeTag(item) { + const info = item.result?.info; + if (item.isEntry) { + // An entry that turned out to be no target is known by its name alone. + if (isNonTarget(item)) return extensionTag(item.name); + return item.kind === 'metadata' + ? metadataTag(info?.metadata?.version ?? item.metadataVersion) + : FORMATS.elf64_aarch64; + } + const known = item.kind === 'package' ? null : observedTag(info?.profile?.observed, info?.metadata?.version); + return known ?? identityTag(item) ?? extensionTag(item.name); +} + +/** + * The route a finished input or entry took, or `null`. An entry names the + * transform that ran on a metadata blob, also one it left as it was; a + * library inside a package has one route only, so none is named for it. + */ +export function routeOf(item) { + const info = item.result?.info; + if (item.isEntry && item.kind === 'so') return null; + const route = item.isEntry ? (info?.metadata?.layout ?? info?.profile?.selected) : info?.profile?.selected; + return route ? tv('layout', route) : null; +} + +/** + * How a row reads: `{ dot, label, tone, extra, time }`. `dot` and `tone` are a + * tone name or `null`; `extra` follows the label and `time` ends the line. + */ +export function rowState(item) { + const plain = (key) => ({ dot: null, label: t(key), tone: null, extra: null, time: null }); + switch (item.state) { + case 'running': + return { ...plain('run.running'), dot: 'info', tone: 'info' }; + case 'queued': + return plain('run.queued'); + case 'cancelled': + return plain('run.will_not_run'); + case 'pending': + return plain(item.notProtected ? 'pending.not_protected' : 'pending.not_run'); + default: { + const { tone, key } = outcomeOf(item); + const time = item.isEntry ? null : timeOf(item); + return { + dot: tone, + label: t(key), + tone, + extra: item.isEntry ? routeOf(item) : t('mode.unpack'), + time: time == null ? null : formatDuration(time), + }; + } + } +} + +/** The pill of an input's state, for the detail head. */ +export function statePill(item) { + const row = rowState(item); + return pill(row.tone ?? 'skip', row.label); +} diff --git a/web/view.js b/web/view.js new file mode 100644 index 0000000..2a213dc --- /dev/null +++ b/web/view.js @@ -0,0 +1,326 @@ +// The frame of the page: the top bar, the inputs pane, the status bar, the +// menus, and the dialogs. Every function returns HTML for one region, from the +// state alone; `app.js` puts it in the document and handles the events. The +// detail pane is in `detail.js`. + +import { LANGUAGES, language, show, t } from './i18n.js'; +import { + VERSION, + allItems, + allOutputs, + counts, + fullPath, + hasSelection, + isDone, + isNonTarget, + outputBusy, + state, + targets, +} from './state.js'; +import { MAX_LIMIT_MIB, MIN_LIMIT_MIB, formatClock } from './model.js'; +import { dot, esc, groupName, modeLabel, rowState, shownPath, stepText, tag, typeTag } from './ui.js'; + +export { esc, groupName } from './ui.js'; +export { detail, logText } from './detail.js'; + +// ---------- inputs ---------- + +const selectable = (id, selected) => + `data-act="select" data-id="${id}" tabindex="0" role="option" aria-selected="${selected}"`; + +const isSelected = (id) => state.selected === id || state.multi.includes(id); + +const caret = (id, open) => + `${open ? '▼' : '▶'}`; + +function rowHtml(item, withCaret) { + const row = rowState(item); + const selected = isSelected(item.id); + const open = !state.collapsed.has(item.id); + const label = `${esc(row.label)}`; + const extra = row.extra ? `·${esc(row.extra)}` : ''; + const time = row.time ? `${esc(row.time)}` : ''; + return ( + `
      ` + + `${withCaret ? caret(item.id, open) : ''}${dot(row.dot)}` + + `${esc(item.name)}${tag(typeTag(item))}` + + `${label}${extra}${time}
      ` + ); +} + +const matches = (name, needle) => needle === '' || name.toLowerCase().includes(needle); + +/** An input's rows: its own, then the entries of a package under it. */ +function itemRows(item, needle) { + const entries = (item.entries ?? []).filter(isDone); + // A search lists every entry it matches; otherwise only the targets show. + const shown = entries.filter((entry) => (needle ? matches(entry.name, needle) : !isNonTarget(entry))); + const others = needle ? 0 : entries.filter(isNonTarget).length; + const rows = [{ key: item.id, html: rowHtml(item, shown.length > 0 || others > 0) }]; + if (state.collapsed.has(item.id)) return rows; + for (const entry of shown) rows.push({ key: entry.id, html: rowHtml(entry, false) }); + if (others) { + rows.push({ + key: `others:${item.id}`, + html: + `
      ` + + `${esc(t('EntriesOthers', { n: others }))}
      `, + }); + } + return rows; +} + +function groupHead(group, shown) { + const selected = state.selected === group.id; + const folder = group.kind === 'folder'; + const path = folder ? shownPath(`${group.name}/`) : ''; + let sub = ''; + if (group.scanning) { + sub = `${esc(t('GroupScanning', { n: group.found }))}`; + } else if (folder) { + sub = `${esc(group.lastRun ? `${modeLabel()} · ${path}` : path)}`; + } + return ( + `
      ` + + `${caret(group.id, !state.collapsed.has(group.id))}` + + `${esc(groupName(group))}` + + `${group.scanning ? group.found : shown}${sub}
      ` + ); +} + +/** The parts of the inputs pane that stay put while its list changes. */ +export function inputsFrame() { + const search = esc(t('inputs.search')); + return ( + `
      ${esc(t('inputs.title'))}` + + `
      ` + + `
      ` + + `
      ` + + `
      ` + ); +} + +/** The filter chips. There are none until an input has a result. */ +export function chips() { + const items = allItems(); + if (!items.some(isDone)) return ''; + const count = counts(items); + return ['all', 'ok', 'suspect', 'failed', 'skipped'] + .map((key) => { + const on = state.filter === key; + return ( + `` + ); + }) + .join(''); +} + +/** + * The rows of the inputs list, each `{ key, html }` with one element of HTML, + * so the page can replace only the rows that changed. + */ +export function listRows() { + const needle = state.search.trim().toLowerCase(); + const filtering = state.filter !== 'all' || needle !== ''; + // A filter chip hides the inputs that finished some other way; an input + // that has not run stays. + const visible = (item) => + !(state.filter !== 'all' && isDone(item) && item.state !== state.filter) && + (matches(item.name, needle) || (item.entries ?? []).some((entry) => matches(entry.name, needle))); + const rows = []; + for (const group of state.groups) { + const items = group.items.filter(visible); + if (filtering && items.length === 0 && !group.scanning) continue; + rows.push({ key: group.id, html: groupHead(group, items.length) }); + if (!state.collapsed.has(group.id)) for (const item of items) rows.push(...itemRows(item, needle)); + } + if (rows.length === 0) rows.push({ key: 'none', html: `

      ${esc(t('inputs.none'))}

      ` }); + return rows; +} + +/** The inputs list as one piece of HTML. */ +export const list = () => listRows().map((row) => row.html).join(''); + +// ---------- top bar and status bar ---------- + +/** Where outputs go, as the output chip and the settings name it. */ +const outputLabel = () => + state.out.mode === 'folder' ? shownPath(`${state.out.dir.name}/unpack`) : t('web.out_downloads'); + +/** True while nothing can be run: a run or a scan is in progress. */ +const busy = () => outputBusy() || state.scans.length > 0; + +export function topbar() { + const count = targets().length; + const label = hasSelection() ? t('TbUnpackN', { n: count }) : t('tb.unpack.all'); + const idle = !busy() && count > 0; + return ( + `
      ` + + `Senbei${VERSION}
      ` + + `` + + `` + + `` + + `` + + `` + + `` + + `` + ); +} + +/** The status line. The Cancel button beside it is the page's own. */ +export function status() { + const run = state.run; + if (run) { + const total = Math.max(run.total, run.done); + const percent = total === 0 ? 0 : Math.round((run.done / total) * 100); + const current = run.current + ? `${esc(run.current.name)}` + + `${run.step ? `${esc(stepText(run.step))}` : ''}` + + `${formatClock(performance.now() - run.started)}` + : ''; + return ( + `●${esc(t('tb.unpack'))}` + + `
      ` + + `
      ${run.done} / ${total}${current}` + + `` + + `${run.stopping ? `${esc(t('run.stopping'))}` : ''}` + ); + } + if (state.scans.length) { + const group = state.scans[0].group; + return `●${esc(t('ScanStatus', { p: groupName(group), n: group.found }))}`; + } + const notice = state.notice + ? `${esc(show(state.notice))}` + : ''; + return `●${esc(t('status.ready'))}${notice}`; +} + +// ---------- menus ---------- + +function choice(act, on, label, sub) { + return ( + `` + ); +} + +/** The output menu. `canPick` says this browser can write to a folder. */ +export function outMenu(canPick) { + const folder = state.out.dir; + const choices = + choice('out-downloads', state.out.mode === 'downloads', t('web.out_downloads')) + + (folder + ? choice('out-folder', state.out.mode === 'folder', t('settings.output_recent'), shownPath(`${folder.name}/unpack`)) + : ''); + const pick = canPick + ? `` + + `

      ${esc(t('web.out_folder_help'))}

      ` + : `

      ${esc(t('web.out_unsupported'))}

      `; + return `${choices}
      ${pick}`; +} + +/** + * The menu of a row. `kind` is `item`, `entry`, or `group`; `runnable` says + * the row can be unpacked, and `busy` that a run is in progress. + */ +export function rowMenu(id, { kind, runnable, busy }) { + const item = (act, label, disabled, shortcut = '') => + ``; + const sep = '
      '; + const remove = item('remove', t('menu.remove'), busy, kind === 'item' ? 'Del' : ''); + if (kind === 'group') return remove; + const top = item('run-item', t('tb.unpack'), busy || !runnable) + sep + item('copy-path', t('menu.copy_path'), false); + return kind === 'entry' ? top : top + sep + remove; +} + +// ---------- dialogs ---------- + +function languageSelect(id) { + const options = LANGUAGES.map( + ([code, name]) => ``, + ); + return ``; +} + +/** The legal notice. Until it is accepted it is the only thing to act on. */ +export function legal(accepted) { + // The four paragraphs are the catalog's own HTML: they carry . + const text = ['legal.p1', 'legal.p2', 'legal.p3', 'legal.p4'].map((key) => `

      ${t(key)}

      `); + const close = accepted + ? `` + : ``; + return ( + `` + + `` + ); +} + +/** A settings row: its label, its control, and an optional help line. */ +function field(id, label, control, help) { + const name = id ? `` : `${esc(label)}`; + const helpId = id ? ` id="${id}-help"` : ''; + return ( + `
      ${name}
      ${control}
      ` + + `${help ? `

      ${esc(help)}

      ` : ''}
      ` + ); +} + +function settingsPane(canPick) { + if (state.settingsTab === 'memory') { + const mib = Math.round(state.limitBytes / (1024 * 1024)); + return field( + 'set-limit', + t('web.limit'), + `MiB`, + t('web.limit_help'), + ); + } + if (state.settingsTab === 'about') { + return ( + `
      Senbei
      ` + + `
      ${esc(t('AboutVersion', { v: VERSION }))}

      ${esc(t('about.desc'))}

      ` + + field(null, t('about.license'), 'AGPL-3.0-only') + + field( + null, + t('about.source'), + 'github.com/Momoko-Ayase/Senbei', + ) + + `
      ` + ); + } + const option = (value, label, on) => ``; + const folder = state.out.dir; + const output = + ``; + const outputHelp = t(canPick ? 'web.out_folder_help' : 'web.out_unsupported'); + return ( + field('set-language', t('settings.language'), languageSelect('set-language')) + + field('set-output', t('settings.output'), output, outputHelp) + ); +} + +/** The settings dialog. `canPick` says this browser can write to a folder. */ +export function settings(canPick) { + const nav = ['general', 'memory', 'about'].map((key) => { + const on = state.settingsTab === key; + return ``; + }); + return ( + `` + + `
      ` + + `
      ${settingsPane(canPick)}
      ` + + `` + ); +} diff --git a/web/worker.js b/web/worker.js index 5c00d8c..74ff17b 100644 --- a/web/worker.js +++ b/web/worker.js @@ -1,97 +1,174 @@ -// One-shot worker: each job runs in a fresh worker with its own wasm instance. -// Two reasons: +// The recovery engine, off the main thread. // -// 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 -// this worker's message handler, which the main thread observes and -// 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. +// The page starts one of these for each job and ends it when the job is done. +// A Rust panic is a trap in WebAssembly and a trapped instance cannot be used +// again, so no instance outlives its job; ending the worker also returns the +// instance's memory, which a recovery grows to a few times the input size. +// Scanning uses a worker that answers several small requests and is replaced +// after a trap. // -// Every reply carries the recovery profile (see `profile_json`), including -// failures: the page shows which route ran and why it was rejected. +// Every request is `{ id, op, ... }` and every reply carries the same `id`. +// The first request also carries `wasm`, the compiled WebAssembly module the +// page shares between workers so that it is fetched and compiled once. import init, { - deobfuscate_metadata_reported, - unpack_file_reported, + InputBuffer, + detect, + inspect_profile_json, + manifest_identity, + probe_library, + restore_library, + restore_metadata, + unpack_pe, + unsafe_package_entry, } from './pkg/senbei_wasm.js'; +import { crc32, entryStream } from './zip.js'; let ready = null; -/** Parse the profile JSON into a plain object for structured cloning. */ -function profileOf(doc) { - if (!doc) return null; +/** + * Copy one input into the instance. + * + * `source` is a `Blob`, or a package entry `{ blob, method, size, crc }` that + * is inflated on the way in and checked against its declared size and CRC. + * The input is never held as a whole on the JS side. + */ +async function load(source) { + const entry = source instanceof Blob ? null : source; + const size = entry ? entry.size : source.size; + const buffer = new InputBuffer(size); + const reader = (entry ? entryStream(entry) : source.stream()).getReader(); + let crc = 0; try { - return JSON.parse(doc); - } catch { - return null; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + // `append` refuses bytes past the declared size, so a malformed entry + // cannot grow the buffer. + buffer.append(value); + if (entry) crc = crc32(value, crc); + } + } catch (error) { + reader.cancel().catch(() => {}); + buffer.free(); + throw error; + } + if (buffer.length !== size) { + buffer.free(); + throw new Error('input is shorter than its declared size'); + } + if (entry && crc !== entry.crc) { + buffer.free(); + throw new Error('package entry does not match its checksum'); + } + return buffer; +} + +/** A copy of a view of the instance's memory, as a `Blob` the page can keep. */ +function blobOf(view) { + return view && view.length > 0 ? new Blob([view]) : null; +} + +/** + * The SHA-256 of a blob in hexadecimal, or `null` where the browser offers no + * digest: `crypto.subtle` exists only in a secure context. + */ +async function digestOf(blob) { + if (!self.crypto?.subtle) return null; + const digest = await self.crypto.subtle.digest('SHA-256', await blob.arrayBuffer()); + return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join(''); +} + +async function recover(id, request) { + const input = await load(request.input); + let companion = null; + let outcome = null; + try { + const onStep = (title, i, of, key) => self.postMessage({ id, type: 'step', title, i, of, key }); + if (request.op === 'pe') { + // `unpack_pe` takes the companion buffer over and frees it. + companion = request.companion ? await load(request.companion) : null; + const taken = companion; + companion = null; + outcome = unpack_pe(input, taken ?? undefined, request.forceExe === true, request.lang, onStep); + } else if (request.op === 'so') { + outcome = restore_library(input, request.lang, onStep); + } else { + outcome = restore_metadata( + input, + request.moduleBytes ?? undefined, + request.conflicting ?? 0, + request.lang, + ); + } + const info = JSON.parse(outcome.info); + // Each view is copied into a Blob before the next call into the module. + const image = blobOf(outcome.image()); + const embedded = blobOf(outcome.embedded_metadata()); + const module = outcome.take_module() ?? null; + self.postMessage({ id, type: 'result', info, image, embedded, module }); + if (info.status !== 'not_protected') { + // Hashing reads every byte again, so it follows the result instead of + // delaying it. + self.postMessage({ + id, + type: 'identity', + input: input.sha256(), + image: image ? outcome.image_sha256() : null, + embedded: embedded ? outcome.embedded_metadata_sha256() ?? null : null, + // The engine gave its copy of the companion back, so the file is read + // once more for its digest, and only when it was the one spliced in. + companion: info.companion && request.companion + ? await digestOf(request.companion).catch(() => null) + : null, + }); + } + self.postMessage({ id, type: 'done' }); + } finally { + outcome?.free(); + companion?.free(); + input.free(); } } -/** 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, - }); +async function handle(request) { + const { id, op } = request; + if (op === 'prefix') { + const kind = detect(request.bytes) ?? null; + const profile = JSON.parse(inspect_profile_json(request.bytes)); + self.postMessage({ id, type: 'done', kind, profile }); + } else if (op === 'probe-so') { + const input = await load(request.input); + try { + self.postMessage({ id, type: 'done', profile: JSON.parse(probe_library(input)) }); + } finally { + input.free(); + } + } else if (op === 'manifest') { + const identity = manifest_identity(request.bytes, request.truncated === true) ?? null; + self.postMessage({ id, type: 'done', identity }); + } else if (op === 'unsafe-entry') { + const message = JSON.parse(unsafe_package_entry(request.package, request.lang)); + self.postMessage({ id, type: 'done', message }); + } else { + await recover(id, request); + } } -self.onmessage = async (e) => { - const { mode, input, companion, forceExe } = e.data; - let profile = null; +self.onmessage = async (event) => { + const request = event.data; try { - ready ??= init(); + ready ??= init({ module_or_path: request.wasm }); await ready; - - 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: 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, - }, - r.ok ? [bytes.buffer] : [], - ); - } catch (err) { - postFailure(err, profile); + await handle(request); + } catch (error) { + self.postMessage({ + id: request.id, + type: 'error', + // A trap leaves the instance unusable. The page ends this worker and, + // for a DLL, tries the other route in a new one. + trap: error instanceof WebAssembly.RuntimeError, + message: String(error?.message ?? error), + }); } }; diff --git a/web/zip.js b/web/zip.js new file mode 100644 index 0000000..e4c3b0e --- /dev/null +++ b/web/zip.js @@ -0,0 +1,388 @@ +// ZIP over `Blob`: read a package's directory and single entries without +// reading the package, and write the "download all" archive without copying +// the outputs. +// +// Reading never trusts a size the archive declares. An entry is inflated by +// the browser's own `DecompressionStream`, and every consumer of that stream +// stops at the declared size, so a malformed entry cannot grow past it. + +const EOCD = 0x06054b50; +const EOCD64 = 0x06064b50; +const EOCD64_LOCATOR = 0x07064b50; +const CENTRAL = 0x02014b50; +const LOCAL = 0x04034b50; +const U32_MAX = 0xffffffff; + +/** A package that cannot be read as a ZIP archive. */ +export class ZipError extends Error { + constructor(message) { + super(message); + this.name = 'ZipError'; + } +} + +const CRC_TABLE = (() => { + const table = new Uint32Array(256); + for (let n = 0; n < 256; n += 1) { + let c = n; + for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + table[n] = c >>> 0; + } + return table; +})(); + +/** CRC-32 of `bytes`, continuing from `crc` (0 to start). */ +export function crc32(bytes, crc = 0) { + let c = ~crc >>> 0; + for (let i = 0; i < bytes.length; i += 1) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8); + return ~c >>> 0; +} + +async function view(blob, start, length) { + if (start < 0 || length < 0 || start + length > blob.size) { + throw new ZipError('archive record lies outside the file'); + } + return new DataView(await blob.slice(start, start + length).arrayBuffer()); +} + +function u64(data, offset) { + const value = data.getBigUint64(offset, true); + if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw new ZipError('archive offset is out of range'); + return Number(value); +} + +function decodeName(bytes, utf8) { + try { + return new TextDecoder('utf-8', { fatal: true }).decode(bytes); + } catch { + if (utf8) throw new ZipError('entry name is not valid UTF-8'); + // A legacy code page. Only ASCII names are ever matched, so a byte-wise + // reading is enough to keep such an entry distinct and listed. + return Array.from(bytes, (byte) => String.fromCharCode(byte)).join(''); + } +} + +/** + * Read the central directory of `blob`. + * + * Returns `{ entries }` in directory order. Each entry is + * `{ name, method, encrypted, crc, compressedSize, size, headerOffset, directory }`. + * Nothing but the directory is read. `limits.maxEntries` and + * `limits.maxDirectoryBytes` are checked before the directory is. + */ +export async function openZip(blob, limits = {}) { + const maxEntries = limits.maxEntries ?? 100_000; + const maxDirectoryBytes = limits.maxDirectoryBytes ?? 64 * 1024 * 1024; + if (blob.size < 22) throw new ZipError('file is too short to be a ZIP archive'); + + const tailLength = Math.min(blob.size, 22 + 0xffff); + const tailStart = blob.size - tailLength; + const tail = await view(blob, tailStart, tailLength); + let at = -1; + for (let i = tailLength - 22; i >= 0; i -= 1) { + if (tail.getUint32(i, true) === EOCD && i + 22 + tail.getUint16(i + 20, true) <= tailLength) { + at = i; + break; + } + } + if (at < 0) throw new ZipError('end-of-directory record not found'); + const eocdOffset = tailStart + at; + if (tail.getUint16(at + 4, true) !== 0 && tail.getUint16(at + 4, true) !== 0xffff) { + throw new ZipError('multi-disk archives are not supported'); + } + let count = tail.getUint16(at + 10, true); + let directorySize = tail.getUint32(at + 12, true); + let directoryOffset = tail.getUint32(at + 16, true); + let directoryEnd = eocdOffset; + + if (count === 0xffff || directorySize === U32_MAX || directoryOffset === U32_MAX) { + if (eocdOffset < 20) throw new ZipError('ZIP64 locator is missing'); + const locator = await view(blob, eocdOffset - 20, 20); + if (locator.getUint32(0, true) !== EOCD64_LOCATOR) throw new ZipError('ZIP64 locator is missing'); + const recordOffset = u64(locator, 8); + const record = await view(blob, recordOffset, 56); + if (record.getUint32(0, true) !== EOCD64) throw new ZipError('ZIP64 directory record is missing'); + count = u64(record, 32); + directorySize = u64(record, 40); + directoryOffset = u64(record, 48); + directoryEnd = recordOffset; + } + if (count > maxEntries) { + throw new ZipError(`archive declares ${count} entries, over the limit of ${maxEntries}`); + } + if (directorySize > maxDirectoryBytes) { + throw new ZipError(`archive directory is ${directorySize} bytes, over the limit`); + } + if (directoryOffset + directorySize > directoryEnd) { + throw new ZipError('archive directory lies outside the file'); + } + if (count * 46 > directorySize) throw new ZipError('archive directory is shorter than its entry count'); + + const directory = await view(blob, directoryOffset, directorySize); + const bytes = new Uint8Array(directory.buffer); + const entries = []; + let cursor = 0; + for (let index = 0; index < count; index += 1) { + if (cursor + 46 > directorySize || directory.getUint32(cursor, true) !== CENTRAL) { + throw new ZipError(`directory entry ${index} is malformed`); + } + const flags = directory.getUint16(cursor + 8, true); + const nameLength = directory.getUint16(cursor + 28, true); + const extraLength = directory.getUint16(cursor + 30, true); + const commentLength = directory.getUint16(cursor + 32, true); + const next = cursor + 46 + nameLength + extraLength + commentLength; + if (next > directorySize) throw new ZipError(`directory entry ${index} is truncated`); + let compressedSize = directory.getUint32(cursor + 20, true); + let size = directory.getUint32(cursor + 24, true); + let headerOffset = directory.getUint32(cursor + 42, true); + + // ZIP64: the 64-bit values follow in this order, each present only when + // its 32-bit field is saturated. + let extra = cursor + 46 + nameLength; + const extraEnd = extra + extraLength; + while (extra + 4 <= extraEnd) { + const id = directory.getUint16(extra, true); + const length = directory.getUint16(extra + 2, true); + let field = extra + 4; + const fieldEnd = field + length; + if (fieldEnd > extraEnd) break; + if (id === 0x0001) { + const take = () => { + if (field + 8 > fieldEnd) throw new ZipError(`directory entry ${index} has a short ZIP64 field`); + const value = u64(directory, field); + field += 8; + return value; + }; + if (size === U32_MAX) size = take(); + if (compressedSize === U32_MAX) compressedSize = take(); + if (headerOffset === U32_MAX) headerOffset = take(); + } + extra = fieldEnd; + } + + const name = decodeName(bytes.subarray(cursor + 46, cursor + 46 + nameLength), (flags & 0x800) !== 0); + entries.push({ + name, + method: directory.getUint16(cursor + 10, true), + encrypted: (flags & 0x1) !== 0, + crc: directory.getUint32(cursor + 16, true), + compressedSize, + size, + headerOffset, + directory: name.endsWith('/'), + }); + cursor = next; + } + return { entries }; +} + +/** + * Locate one entry's data. + * + * Returns `{ blob, method, size, crc }`, where `blob` is the entry's stored + * bytes as a slice of the archive. Only the entry's 30-byte local header is + * read. An encrypted entry, or a compression method other than stored and + * deflate, is refused. + */ +export async function entrySource(blob, entry) { + if (entry.encrypted) throw new ZipError(`entry ${entry.name} is encrypted`); + if (entry.method !== 0 && entry.method !== 8) { + throw new ZipError(`entry ${entry.name} uses unsupported compression method ${entry.method}`); + } + if (entry.method === 0 && entry.size !== entry.compressedSize) { + throw new ZipError(`stored entry ${entry.name} declares two different sizes`); + } + const header = await view(blob, entry.headerOffset, 30); + if (header.getUint32(0, true) !== LOCAL) throw new ZipError(`entry ${entry.name} has no local header`); + const start = entry.headerOffset + 30 + header.getUint16(26, true) + header.getUint16(28, true); + if (start + entry.compressedSize > blob.size) { + throw new ZipError(`entry ${entry.name} lies outside the file`); + } + return { + blob: blob.slice(start, start + entry.compressedSize), + method: entry.method, + size: entry.size, + crc: entry.crc, + }; +} + +/** The entry's bytes as a stream, inflated when it is deflated. */ +export function entryStream(source) { + const stream = source.blob.stream(); + return source.method === 8 ? stream.pipeThrough(new DecompressionStream('deflate-raw')) : stream; +} + +/** + * Read at most `limit` bytes from the start of an entry. + * + * Returns `{ bytes, truncated }`. `truncated` says the entry is longer than + * what was read. Nothing past `limit` is inflated. + */ +export async function readEntryPrefix(source, limit) { + const wanted = Math.min(limit, source.size); + const bytes = new Uint8Array(wanted); + let length = 0; + const reader = entryStream(source).getReader(); + try { + while (length < wanted) { + const { done, value } = await reader.read(); + if (done) break; + const take = Math.min(value.length, wanted - length); + bytes.set(value.subarray(0, take), length); + length += take; + } + } finally { + reader.cancel().catch(() => {}); + } + return { bytes: bytes.subarray(0, length), truncated: source.size > limit }; +} + +/** + * A whole entry as a `Blob`, checked against its declared size and CRC. + * + * A stored entry is returned as a slice of the archive, with nothing read but + * what the CRC check streams through. `limit` bounds the declared size. + */ +export async function entryBlob(source, limit) { + if (source.size > limit) { + throw new ZipError(`entry is ${source.size} bytes, over the ${limit}-byte limit`); + } + const parts = []; + let length = 0; + let crc = 0; + const reader = entryStream(source).getReader(); + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + length += value.length; + if (length > source.size) { + reader.cancel().catch(() => {}); + throw new ZipError('entry is longer than its declared size'); + } + crc = crc32(value, crc); + if (source.method !== 0) parts.push(value); + } + if (length !== source.size) throw new ZipError('entry is shorter than its declared size'); + if (crc !== source.crc) throw new ZipError('entry does not match its checksum'); + return source.method === 0 ? source.blob : new Blob(parts); +} + +async function blobCrc(blob) { + let crc = 0; + const reader = blob.stream().getReader(); + for (;;) { + const { done, value } = await reader.read(); + if (done) return crc; + crc = crc32(value, crc); + } +} + +function dosTime(date) { + const year = Math.max(1980, Math.min(2107, date.getFullYear())); + return { + time: (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1), + date: ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate(), + }; +} + +/** + * Build an uncompressed ZIP archive of `files` (`{ path, blob }` each). + * + * The result references the given blobs; only the headers are new bytes. + * Sizes or offsets past 4 GiB, and more than 65,535 files, use ZIP64 records. + */ +export async function buildZip(files, now = new Date()) { + const stamp = dosTime(now); + const encoder = new TextEncoder(); + const parts = []; + const central = []; + let offset = 0; + + for (const file of files) { + const name = encoder.encode(file.path); + const size = file.blob.size; + const crc = await blobCrc(file.blob); + const big = size >= U32_MAX; + const farAway = offset >= U32_MAX; + + const localExtra = big ? 20 : 0; + const local = new DataView(new ArrayBuffer(30 + name.length + localExtra)); + local.setUint32(0, LOCAL, true); + local.setUint16(4, big ? 45 : 20, true); + local.setUint16(6, 0x800, true); + local.setUint16(10, stamp.time, true); + local.setUint16(12, stamp.date, true); + local.setUint32(14, crc, true); + local.setUint32(18, big ? U32_MAX : size, true); + local.setUint32(22, big ? U32_MAX : size, true); + local.setUint16(26, name.length, true); + local.setUint16(28, localExtra, true); + new Uint8Array(local.buffer).set(name, 30); + if (big) { + local.setUint16(30 + name.length, 0x0001, true); + local.setUint16(32 + name.length, 16, true); + local.setBigUint64(34 + name.length, BigInt(size), true); + local.setBigUint64(42 + name.length, BigInt(size), true); + } + + const extraLength = big || farAway ? 4 + (big ? 16 : 0) + (farAway ? 8 : 0) : 0; + const record = new DataView(new ArrayBuffer(46 + name.length + extraLength)); + record.setUint32(0, CENTRAL, true); + record.setUint16(4, 45, true); + record.setUint16(6, big || farAway ? 45 : 20, true); + record.setUint16(8, 0x800, true); + record.setUint16(12, stamp.time, true); + record.setUint16(14, stamp.date, true); + record.setUint32(16, crc, true); + record.setUint32(20, big ? U32_MAX : size, true); + record.setUint32(24, big ? U32_MAX : size, true); + record.setUint16(28, name.length, true); + record.setUint16(30, extraLength, true); + record.setUint32(42, farAway ? U32_MAX : offset, true); + new Uint8Array(record.buffer).set(name, 46); + if (extraLength) { + let field = 46 + name.length; + record.setUint16(field, 0x0001, true); + record.setUint16(field + 2, extraLength - 4, true); + field += 4; + if (big) { + record.setBigUint64(field, BigInt(size), true); + record.setBigUint64(field + 8, BigInt(size), true); + field += 16; + } + if (farAway) record.setBigUint64(field, BigInt(offset), true); + } + + parts.push(local.buffer, file.blob); + central.push(record.buffer); + offset += local.byteLength + size; + } + + const directoryOffset = offset; + const directorySize = central.reduce((sum, record) => sum + record.byteLength, 0); + parts.push(...central); + const count = files.length; + if (count > 0xffff || directorySize >= U32_MAX || directoryOffset >= U32_MAX) { + const record = new DataView(new ArrayBuffer(56 + 20)); + record.setUint32(0, EOCD64, true); + record.setBigUint64(4, 44n, true); + record.setUint16(12, 45, true); + record.setUint16(14, 45, true); + record.setBigUint64(24, BigInt(count), true); + record.setBigUint64(32, BigInt(count), true); + record.setBigUint64(40, BigInt(directorySize), true); + record.setBigUint64(48, BigInt(directoryOffset), true); + record.setUint32(56, EOCD64_LOCATOR, true); + record.setBigUint64(64, BigInt(directoryOffset + directorySize), true); + record.setUint32(72, 1, true); + parts.push(record.buffer); + } + const end = new DataView(new ArrayBuffer(22)); + end.setUint32(0, EOCD, true); + end.setUint16(8, Math.min(count, 0xffff), true); + end.setUint16(10, Math.min(count, 0xffff), true); + end.setUint32(12, Math.min(directorySize, U32_MAX), true); + end.setUint32(16, Math.min(directoryOffset, U32_MAX), true); + parts.push(end.buffer); + return new Blob(parts, { type: 'application/zip' }); +}