mirror of
https://github.com/Momoko-Ayase/Senbei.git
synced 2026-11-25 02:52:47 +08:00
feat(web): bring the Senbei workbench to the browser
Add folder scanning, Android library and package recovery, and the localized desktop-style workbench. Keep browser-refused outputs in a fallback ZIP and include logs with folder and ZIP exports. Align the desktop and web modal transitions and polish the desktop About and legal dialogs.
This commit is contained in:
1 parent
20a68b1c73
commit
21236e8b98
59 files changed
+11612
-3436
No files matched your search
@@ -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
|
||||
@@ -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 }}
|
||||
|
||||
@@ -229,3 +229,79 @@ fn android_samples_restore_against_goldens() {
|
||||
);
|
||||
assert!(failures.is_empty(), "{}", failures.join("\n"));
|
||||
}
|
||||
|
||||
/// The byte-level restore the browser binding uses must produce the bytes the
|
||||
/// path-based driver writes: the same image, the same embedded metadata, and a
|
||||
/// failure for the same inputs.
|
||||
#[test]
|
||||
fn android_samples_restore_identically_in_memory() {
|
||||
let root = corpus_dir();
|
||||
if !root.is_dir() {
|
||||
eprintln!(
|
||||
"android samples: {} does not exist, nothing to test",
|
||||
root.display()
|
||||
);
|
||||
return;
|
||||
}
|
||||
let limits = senbei_engine::android::ResourceLimits::default();
|
||||
let mut compared = 0usize;
|
||||
let mut failures: Vec<String> = Vec::new();
|
||||
|
||||
for app in app_dirs(&root) {
|
||||
let mut so_files = Vec::new();
|
||||
collect_so_files(&app, &mut so_files);
|
||||
for input in so_files {
|
||||
let name = input.file_name().unwrap().to_string_lossy().to_string();
|
||||
let bytes = std::fs::read(&input).expect("read sample");
|
||||
let on_disk_protected = android::is_protected_so_file(&input);
|
||||
let (profile, outcome) = android::restore_library_bytes(&bytes, false, &limits);
|
||||
if !on_disk_protected {
|
||||
if !matches!(outcome, android::LibraryOutcome::NotProtected) {
|
||||
failures.push(format!(
|
||||
"{name}: the file probe says unprotected, the byte probe disagrees"
|
||||
));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let temp = tempfile::tempdir().expect("tempdir");
|
||||
let dest = temp.path().join("restored.so");
|
||||
let on_disk = android::restore_so_file(&input, &dest, false);
|
||||
compared += 1;
|
||||
match (on_disk, outcome) {
|
||||
(Ok(embedded), android::LibraryOutcome::Restored(restored)) => {
|
||||
let written = std::fs::read(&dest).expect("read restored output");
|
||||
if written != restored.image {
|
||||
failures.push(format!(
|
||||
"{name}: in-memory image differs from the written file\n file sha256 {}\n memory sha256 {}",
|
||||
sha256_hex(&written),
|
||||
sha256_hex(&restored.image)
|
||||
));
|
||||
}
|
||||
if embedded != restored.embedded_metadata {
|
||||
failures.push(format!("{name}: embedded metadata differs"));
|
||||
}
|
||||
if profile.recovery != senbei_engine::RecoveryStatus::Succeeded {
|
||||
failures.push(format!("{name}: restored without a recovered profile"));
|
||||
}
|
||||
}
|
||||
(Err(_), android::LibraryOutcome::Failed(_)) => {}
|
||||
(Ok(_), android::LibraryOutcome::Failed(detail)) => failures.push(format!(
|
||||
"{name}: the file restore succeeded, the byte restore failed: {}",
|
||||
detail.text()
|
||||
)),
|
||||
(Ok(_), _) => failures.push(format!(
|
||||
"{name}: the file restore succeeded, the byte probe did not match"
|
||||
)),
|
||||
(Err(error), _) => failures.push(format!(
|
||||
"{name}: the file restore failed ({error:#}), the byte restore did not"
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eprintln!(
|
||||
"android samples: {compared} protected libraries compared, {} difference(s)",
|
||||
failures.len()
|
||||
);
|
||||
assert!(failures.is_empty(), "{}", failures.join("\n"));
|
||||
}
|
||||
+309
-187
@@ -1,15 +1,17 @@
|
||||
//! Native/WASM parity over the same byte API.
|
||||
//!
|
||||
//! The browser binding calls `senbei_io::job::unpack_bytes`,
|
||||
//! `..._force_exe`, `senbei_metadata::deobfuscate`, and
|
||||
//! The browser binding calls `senbei_io::job::unpack_bytes_profiled`,
|
||||
//! `..._force_exe_profiled`, `senbei_io::android::restore_library_bytes`,
|
||||
//! `senbei_io::android::restore_metadata_bytes_profiled`, and
|
||||
//! `senbei_engine::detect`. This test feeds the *same* fixtures to the native
|
||||
//! functions and to a `wasm-pack --target nodejs` build of `senbei-wasm`, and
|
||||
//! compares kind, byte length, SHA-256, remap counts, and suspect state.
|
||||
//! compares the recovery profile, kind, byte length, SHA-256, remap counts,
|
||||
//! and suspect state.
|
||||
//!
|
||||
//! What this does NOT prove: it uses synthetic, hand-built fixtures only. It
|
||||
//! says nothing about real protected PE recovery, real Android restoration, or
|
||||
//! arbitrary third-party binaries — those need fixtures in the corpus and are
|
||||
//! deliberately out of scope here.
|
||||
//! What the default run does NOT prove: it uses synthetic, hand-built fixtures
|
||||
//! only. It says nothing about real protected PE recovery, real Android
|
||||
//! restoration, or arbitrary third-party binaries. Those are compared only
|
||||
//! when a private corpus is named (see below).
|
||||
//!
|
||||
//! The test is opt-in because it needs a wasm build:
|
||||
//!
|
||||
@@ -24,6 +26,8 @@
|
||||
//! the node binary. Private-corpus parity can be requested by setting
|
||||
//! `SENBEI_WASM_PARITY_CORPUS=<manifest.json>`: every `pe`/`metadata` case in
|
||||
//! that harness manifest is also compared, still without writing any output.
|
||||
//! With `SENBEI_ANDROID_SAMPLES=<dir>` set, every `.so` of every app tree in
|
||||
//! that directory is restored on both sides and compared as well.
|
||||
|
||||
#[path = "support/fixtures.rs"]
|
||||
mod fixtures;
|
||||
@@ -131,156 +135,15 @@ fn wasm_parity_is_opt_in_and_reports_why() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_byte_transforms_match_wasm() {
|
||||
if !enabled() {
|
||||
eprintln!("wasm parity skipped (SENBEI_WASM_PARITY not set)");
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut jobs = Vec::new();
|
||||
let mut native = Vec::new();
|
||||
|
||||
// Detection: every variant plus a non-target.
|
||||
for (name, dll, managed) in [
|
||||
("native-exe.bin", false, false),
|
||||
("native-dll.bin", true, false),
|
||||
("managed-exe.bin", false, true),
|
||||
("managed-dll.bin", true, true),
|
||||
] {
|
||||
let bytes = fixtures::synthetic_crackproof_pe(dll, managed);
|
||||
let path = write_fixture(dir.path(), name, &bytes);
|
||||
jobs.push(WasmJob {
|
||||
op: "detect",
|
||||
input: path,
|
||||
companion: None,
|
||||
});
|
||||
native.push(native_detect(&bytes));
|
||||
}
|
||||
let plain = write_fixture(dir.path(), "plain.bin", &fixtures::synthetic_plain_pe());
|
||||
jobs.push(WasmJob {
|
||||
op: "detect",
|
||||
input: plain,
|
||||
companion: None,
|
||||
});
|
||||
native.push(json!({ "ok": true, "kind": null }));
|
||||
|
||||
// Metadata: clean (idempotent) and obfuscated (5 rewrites).
|
||||
let mut metadata_native = Vec::new();
|
||||
for (name, bytes) in [
|
||||
("clean.dat", fixtures::clean_metadata()),
|
||||
("obfuscated.dat", fixtures::obfuscated_metadata()),
|
||||
] {
|
||||
let path = write_fixture(dir.path(), name, &bytes);
|
||||
jobs.push(WasmJob {
|
||||
op: "metadata",
|
||||
input: path,
|
||||
companion: None,
|
||||
});
|
||||
let (out, report) = senbei_metadata::deobfuscate(&bytes).unwrap();
|
||||
metadata_native.push(json!({
|
||||
"ok": true,
|
||||
"bytes": out.len(),
|
||||
"sha256": sha256_hex(&out),
|
||||
"version": report.version,
|
||||
"methods": report.methods,
|
||||
"remapped": report.remapped,
|
||||
"modules": report.modules,
|
||||
}));
|
||||
}
|
||||
|
||||
// Metadata probes: both sides must reject with the same error text.
|
||||
let mut probe_native = Vec::new();
|
||||
for (name, bytes) in fixtures::malformed_metadata_probes() {
|
||||
let path = write_fixture(dir.path(), &format!("probe-{name}.dat"), &bytes);
|
||||
jobs.push(WasmJob {
|
||||
op: "metadata",
|
||||
input: path,
|
||||
companion: None,
|
||||
});
|
||||
probe_native.push(match senbei_metadata::deobfuscate(&bytes) {
|
||||
Ok(_) => json!({ "ok": false, "error": "unexpected success" }),
|
||||
Err(error) => json!({ "ok": false, "error": error.to_string() }),
|
||||
});
|
||||
}
|
||||
|
||||
// Native unpack for every detection fixture: both sides must agree on the
|
||||
// error wording for these non-protected/header-only inputs.
|
||||
let mut unpack_native = Vec::new();
|
||||
for (name, dll, managed) in [
|
||||
("u-native-exe.bin", false, false),
|
||||
("u-native-dll.bin", true, false),
|
||||
("u-managed-exe.bin", false, true),
|
||||
("u-managed-dll.bin", true, true),
|
||||
] {
|
||||
let bytes = fixtures::synthetic_crackproof_pe(dll, managed);
|
||||
let path = write_fixture(dir.path(), name, &bytes);
|
||||
jobs.push(WasmJob {
|
||||
op: "unpack",
|
||||
input: path.clone(),
|
||||
companion: None,
|
||||
});
|
||||
unpack_native.push(match senbei_io::job::unpack_bytes(&bytes, None) {
|
||||
Ok(image) => json!({
|
||||
"ok": true,
|
||||
"kind": kind_name(image.kind),
|
||||
"bytes": image.bytes.len(),
|
||||
"sha256": sha256_hex(&image.bytes),
|
||||
"suspect": !image.integrity.ok(),
|
||||
"issues": image.integrity.issues,
|
||||
"companion": image.companion,
|
||||
}),
|
||||
Err(error) => json!({ "ok": false, "error": error.to_string() }),
|
||||
});
|
||||
// Force-exe is the browser's recovery path; it must agree too.
|
||||
let path2 = write_fixture(dir.path(), &format!("{name}.force"), &bytes);
|
||||
jobs.push(WasmJob {
|
||||
op: "unpack_force_exe",
|
||||
input: path2,
|
||||
companion: None,
|
||||
});
|
||||
unpack_native.push(match senbei_io::job::unpack_bytes_force_exe(&bytes, None) {
|
||||
Ok(image) => json!({
|
||||
"ok": true,
|
||||
"kind": kind_name(image.kind),
|
||||
"bytes": image.bytes.len(),
|
||||
"sha256": sha256_hex(&image.bytes),
|
||||
"suspect": !image.integrity.ok(),
|
||||
"issues": image.integrity.issues,
|
||||
"companion": image.companion,
|
||||
}),
|
||||
Err(error) => json!({ "ok": false, "error": error.to_string() }),
|
||||
});
|
||||
}
|
||||
|
||||
let results = run_wasm(&jobs);
|
||||
// Negative control: the driver must have produced a real SHA-256 for the
|
||||
// clean metadata. If the WASM call silently no-op'd, this would not match
|
||||
// the native digest and the control would fail before the loop below.
|
||||
let clean_index = jobs
|
||||
.iter()
|
||||
.position(|job| job.op == "metadata")
|
||||
.expect("metadata jobs exist");
|
||||
let native_clean = &metadata_native[0];
|
||||
assert_eq!(
|
||||
results[clean_index]["sha256"], native_clean["sha256"],
|
||||
"negative control: wasm metadata digest must match native"
|
||||
);
|
||||
let all_native: Vec<Value> = native
|
||||
.into_iter()
|
||||
.chain(metadata_native)
|
||||
.chain(probe_native)
|
||||
.chain(unpack_native)
|
||||
.collect();
|
||||
for (index, (want, got)) in all_native.iter().zip(&results).enumerate() {
|
||||
assert_eq!(
|
||||
want,
|
||||
got,
|
||||
"parity mismatch at job {index} ({}):\nnative {want}\nwasm {got}",
|
||||
jobs.get(index).map(|job| job.op).unwrap_or("?")
|
||||
);
|
||||
}
|
||||
}
|
||||
/// The ceilings the browser binding restores under. They must stay the ones
|
||||
/// in `senbei-wasm/src/lib.rs`, or the two sides stop at different points.
|
||||
const BROWSER_LIMITS: senbei_engine::android::ResourceLimits =
|
||||
senbei_engine::android::ResourceLimits {
|
||||
max_entry_bytes: 1 << 30,
|
||||
max_total_bytes: 4 << 30,
|
||||
max_entries: 100_000,
|
||||
max_depth: 32,
|
||||
};
|
||||
|
||||
fn native_detect(bytes: &[u8]) -> Value {
|
||||
match senbei_engine::detect(bytes) {
|
||||
@@ -298,6 +161,217 @@ fn kind_name(kind: senbei_engine::Kind) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the binding's `unpack_pe` reports, computed natively.
|
||||
fn native_unpack(bytes: &[u8], companion: Option<&[u8]>, force_exe: bool) -> Value {
|
||||
let (profile, result) = if force_exe {
|
||||
senbei_io::job::unpack_bytes_force_exe_profiled(bytes, companion)
|
||||
} else {
|
||||
senbei_io::job::unpack_bytes_profiled(bytes, companion)
|
||||
};
|
||||
match result {
|
||||
Ok(image) => json!({
|
||||
"ok": true,
|
||||
"kind": kind_name(image.kind),
|
||||
"bytes": image.bytes.len(),
|
||||
"sha256": sha256_hex(&image.bytes),
|
||||
"suspect": !image.integrity.ok(),
|
||||
"issues": image.integrity.issues.iter().map(ToString::to_string).collect::<Vec<_>>(),
|
||||
"companion": image.companion,
|
||||
"profile": profile,
|
||||
}),
|
||||
Err(error) => json!({
|
||||
"ok": false,
|
||||
"error": error.message().text(),
|
||||
"profile": profile,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the binding's `restore_metadata` reports, computed natively.
|
||||
fn native_metadata(bytes: &[u8]) -> Value {
|
||||
use senbei_io::android::{MetadataOutcome, ModuleBinding, restore_metadata_bytes_profiled};
|
||||
let (profile, outcome) = restore_metadata_bytes_profiled(bytes, ModuleBinding::None);
|
||||
let reported = |status: &str,
|
||||
out: Option<&[u8]>,
|
||||
report: &senbei_metadata::Report,
|
||||
layout: &senbei_engine::LayoutKind| {
|
||||
json!({
|
||||
"ok": true,
|
||||
"status": status,
|
||||
"bytes": out.map_or(0, <[u8]>::len),
|
||||
"sha256": out.map(sha256_hex),
|
||||
"version": report.version,
|
||||
"methods": report.methods,
|
||||
"remapped": report.remapped,
|
||||
"modules": report.modules,
|
||||
"layout": layout,
|
||||
"profile": &profile,
|
||||
})
|
||||
};
|
||||
match &outcome {
|
||||
MetadataOutcome::Restored {
|
||||
bytes,
|
||||
report,
|
||||
layout,
|
||||
} => reported("recovered", Some(bytes), report, layout),
|
||||
MetadataOutcome::Unchanged { report, layout } => {
|
||||
reported("unchanged", None, report, layout)
|
||||
}
|
||||
MetadataOutcome::Unsupported { .. } => json!({
|
||||
"ok": true,
|
||||
"status": "unsupported",
|
||||
"bytes": 0,
|
||||
"sha256": null,
|
||||
"version": profile.observed.metadata_version,
|
||||
"methods": null,
|
||||
"remapped": null,
|
||||
"modules": null,
|
||||
"layout": null,
|
||||
"profile": &profile,
|
||||
}),
|
||||
MetadataOutcome::Failed(error) => json!({
|
||||
"ok": false,
|
||||
"error": error.text(),
|
||||
"profile": &profile,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the binding's `restore_library` reports, computed natively.
|
||||
fn native_library(bytes: &[u8]) -> Value {
|
||||
use senbei_io::android::{LibraryOutcome, restore_library_bytes};
|
||||
let (profile, outcome) = restore_library_bytes(bytes, false, &BROWSER_LIMITS);
|
||||
match outcome {
|
||||
LibraryOutcome::Restored(restored) => json!({
|
||||
"ok": true,
|
||||
"status": "recovered",
|
||||
"bytes": restored.image.len(),
|
||||
"sha256": sha256_hex(&restored.image),
|
||||
"embedded": restored.embedded_metadata.as_deref().map(sha256_hex),
|
||||
"module": restored.method_index_module.as_deref().map(sha256_hex),
|
||||
"elf": restored.elf,
|
||||
"profile": profile,
|
||||
}),
|
||||
LibraryOutcome::NotProtected => json!({
|
||||
"ok": true,
|
||||
"status": "not_protected",
|
||||
"bytes": 0,
|
||||
"sha256": null,
|
||||
"embedded": null,
|
||||
"module": null,
|
||||
"elf": null,
|
||||
"profile": profile,
|
||||
}),
|
||||
LibraryOutcome::Failed(error) => json!({
|
||||
"ok": false,
|
||||
"error": error.text(),
|
||||
"profile": profile,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_parity(jobs: &[WasmJob], native: &[Value], results: &[Value]) {
|
||||
assert_eq!(native.len(), results.len(), "one native result per job");
|
||||
for (index, (want, got)) in native.iter().zip(results).enumerate() {
|
||||
assert_eq!(
|
||||
want,
|
||||
got,
|
||||
"parity mismatch at job {index} ({} {}):\nnative {want}\nwasm {got}",
|
||||
jobs[index].op,
|
||||
jobs[index].input.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_byte_transforms_match_wasm() {
|
||||
if !enabled() {
|
||||
eprintln!("wasm parity skipped (SENBEI_WASM_PARITY not set)");
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut jobs = Vec::new();
|
||||
let mut native = Vec::new();
|
||||
let mut job = |op: &'static str, name: &str, bytes: &[u8]| {
|
||||
jobs.push(WasmJob {
|
||||
op,
|
||||
input: write_fixture(dir.path(), name, bytes),
|
||||
companion: None,
|
||||
});
|
||||
};
|
||||
let variants = [
|
||||
("native-exe.bin", false, false),
|
||||
("native-dll.bin", true, false),
|
||||
("managed-exe.bin", false, true),
|
||||
("managed-dll.bin", true, true),
|
||||
];
|
||||
|
||||
// Detection: every variant plus a non-target.
|
||||
for (name, dll, managed) in variants {
|
||||
let bytes = fixtures::synthetic_crackproof_pe(dll, managed);
|
||||
job("detect", name, &bytes);
|
||||
native.push(native_detect(&bytes));
|
||||
}
|
||||
let plain = fixtures::synthetic_plain_pe();
|
||||
job("detect", "plain.bin", &plain);
|
||||
native.push(json!({ "ok": true, "kind": null }));
|
||||
|
||||
// Metadata: clean (validated, nothing to rewrite) and obfuscated (5
|
||||
// rewrites), then blobs both sides must refuse in the same words.
|
||||
let metadata_start = native.len();
|
||||
for (name, bytes) in [
|
||||
("clean.dat", fixtures::clean_metadata()),
|
||||
("obfuscated.dat", fixtures::obfuscated_metadata()),
|
||||
] {
|
||||
job("metadata", name, &bytes);
|
||||
native.push(native_metadata(&bytes));
|
||||
}
|
||||
for (name, bytes) in fixtures::malformed_metadata_probes() {
|
||||
job("metadata", &format!("probe-{name}.dat"), &bytes);
|
||||
native.push(native_metadata(&bytes));
|
||||
}
|
||||
|
||||
// Unpack for every detection fixture, by both routes: the two sides must
|
||||
// agree on the profile and the error wording for these header-only inputs.
|
||||
// The EXE-only route is the page's retry after a trap.
|
||||
for (name, dll, managed) in variants {
|
||||
let bytes = fixtures::synthetic_crackproof_pe(dll, managed);
|
||||
job("unpack", &format!("u-{name}"), &bytes);
|
||||
native.push(native_unpack(&bytes, None, false));
|
||||
job("unpack_force_exe", &format!("f-{name}"), &bytes);
|
||||
native.push(native_unpack(&bytes, None, true));
|
||||
}
|
||||
|
||||
// Library: inputs that are not protected AArch64 libraries.
|
||||
for (name, bytes) in [
|
||||
("plain.so", plain.clone()),
|
||||
("stub.so", b"\x7fELF\x02\x01\x01".to_vec()),
|
||||
("empty.so", Vec::new()),
|
||||
] {
|
||||
job("library", name, &bytes);
|
||||
native.push(native_library(&bytes));
|
||||
}
|
||||
|
||||
let results = run_wasm(&jobs);
|
||||
// Negative control: the driver must have rewritten the obfuscated blob and
|
||||
// hashed real bytes. If the WASM call silently did nothing, the status and
|
||||
// digest would not be these.
|
||||
assert_eq!(
|
||||
results[metadata_start]["status"], "unchanged",
|
||||
"clean metadata needs no rewrite"
|
||||
);
|
||||
let rewritten = &results[metadata_start + 1];
|
||||
assert_eq!(rewritten["status"], "recovered", "{rewritten}");
|
||||
assert_eq!(rewritten["remapped"], 5, "{rewritten}");
|
||||
assert!(rewritten["sha256"].is_string());
|
||||
assert_eq!(
|
||||
rewritten["sha256"],
|
||||
native[metadata_start + 1]["sha256"],
|
||||
"negative control: wasm metadata digest must match native"
|
||||
);
|
||||
assert_parity(&jobs, &native, &results);
|
||||
}
|
||||
|
||||
/// Optional: compare private corpus cases as well, when a harness manifest and
|
||||
/// the gate are both provided. Restored bytes still go nowhere.
|
||||
#[test]
|
||||
@@ -327,45 +401,21 @@ fn optional_private_corpus_parity() {
|
||||
let comp = companion
|
||||
.as_ref()
|
||||
.map(|path| std::fs::read(path).expect("read companion"));
|
||||
native.push(native_unpack(&bytes, comp.as_deref(), false));
|
||||
jobs.push(WasmJob {
|
||||
op: "unpack",
|
||||
input: input.clone(),
|
||||
companion: companion.clone(),
|
||||
input,
|
||||
companion,
|
||||
});
|
||||
native.push(
|
||||
match senbei_io::job::unpack_bytes(&bytes, comp.as_deref()) {
|
||||
Ok(image) => json!({
|
||||
"ok": true,
|
||||
"kind": kind_name(image.kind),
|
||||
"bytes": image.bytes.len(),
|
||||
"sha256": sha256_hex(&image.bytes),
|
||||
"suspect": !image.integrity.ok(),
|
||||
"issues": image.integrity.issues,
|
||||
"companion": image.companion,
|
||||
}),
|
||||
Err(error) => json!({ "ok": false, "error": error.to_string() }),
|
||||
},
|
||||
);
|
||||
}
|
||||
"metadata" => {
|
||||
let bytes = std::fs::read(&input).expect("read corpus metadata");
|
||||
native.push(native_metadata(&bytes));
|
||||
jobs.push(WasmJob {
|
||||
op: "metadata",
|
||||
input,
|
||||
companion: None,
|
||||
});
|
||||
native.push(match senbei_metadata::deobfuscate(&bytes) {
|
||||
Ok((out, detail)) => json!({
|
||||
"ok": true,
|
||||
"bytes": out.len(),
|
||||
"sha256": sha256_hex(&out),
|
||||
"version": detail.version,
|
||||
"methods": detail.methods,
|
||||
"remapped": detail.remapped,
|
||||
"modules": detail.modules,
|
||||
}),
|
||||
Err(error) => json!({ "ok": false, "error": error.to_string() }),
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -375,11 +425,83 @@ fn optional_private_corpus_parity() {
|
||||
return;
|
||||
}
|
||||
let results = run_wasm(&jobs);
|
||||
for (want, got) in native.iter().zip(&results) {
|
||||
assert_eq!(want, got, "private corpus parity mismatch");
|
||||
assert_parity(&jobs, &native, &results);
|
||||
}
|
||||
|
||||
/// Every `.so` below `dir`, skipping previous output trees.
|
||||
fn collect_libraries(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let mut entries: Vec<PathBuf> = std::fs::read_dir(dir)
|
||||
.unwrap_or_else(|error| panic!("read {}: {error}", dir.display()))
|
||||
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
|
||||
.collect();
|
||||
entries.sort();
|
||||
for path in entries {
|
||||
if path.is_dir() {
|
||||
if path
|
||||
.file_name()
|
||||
.is_some_and(|name| !name.eq_ignore_ascii_case("unpack"))
|
||||
{
|
||||
collect_libraries(&path, out);
|
||||
}
|
||||
} else if path
|
||||
.extension()
|
||||
.is_some_and(|extension| extension.eq_ignore_ascii_case("so"))
|
||||
{
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Optional: restore every library of the private Android corpus on both
|
||||
/// sides. Each app tree is an immediate subdirectory with a `lib/` folder.
|
||||
#[test]
|
||||
fn optional_android_corpus_parity() {
|
||||
if !enabled() {
|
||||
return;
|
||||
}
|
||||
let Some(root) = std::env::var_os("SENBEI_ANDROID_SAMPLES").map(PathBuf::from) else {
|
||||
return;
|
||||
};
|
||||
let mut apps: Vec<PathBuf> = std::fs::read_dir(&root)
|
||||
.unwrap_or_else(|error| panic!("read {}: {error}", root.display()))
|
||||
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
|
||||
.filter(|path| path.join("lib").is_dir())
|
||||
.collect();
|
||||
apps.sort();
|
||||
let mut libraries = Vec::new();
|
||||
for app in apps {
|
||||
collect_libraries(&app.join("lib"), &mut libraries);
|
||||
}
|
||||
if libraries.is_empty() {
|
||||
eprintln!(
|
||||
"android corpus parity: no libraries under {}",
|
||||
root.display()
|
||||
);
|
||||
return;
|
||||
}
|
||||
let mut jobs = Vec::new();
|
||||
let mut native = Vec::new();
|
||||
for input in libraries {
|
||||
let bytes = std::fs::read(&input).expect("read corpus library");
|
||||
native.push(native_library(&bytes));
|
||||
jobs.push(WasmJob {
|
||||
op: "library",
|
||||
input,
|
||||
companion: None,
|
||||
});
|
||||
}
|
||||
let restored = native
|
||||
.iter()
|
||||
.filter(|result| result["status"] == "recovered")
|
||||
.count();
|
||||
eprintln!(
|
||||
"android corpus parity: {} libraries, {restored} restored natively",
|
||||
jobs.len()
|
||||
);
|
||||
let results = run_wasm(&jobs);
|
||||
assert_parity(&jobs, &native, &results);
|
||||
}
|
||||
|
||||
/// Minimal in-process harness invocation shared with the example's module.
|
||||
fn harness_run(manifest: &Path) -> Value {
|
||||
#[path = "support/harness.rs"]
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
// Native/WASM parity driver. Reads a JSON job list on stdin and prints one
|
||||
// JSON result per job on stdout. The Rust test starts `node` with this file.
|
||||
//
|
||||
// Job: { "op": "detect" | "unpack" | "unpack_force_exe" | "metadata",
|
||||
// Job: { "op": "detect" | "unpack" | "unpack_force_exe" | "metadata" | "library",
|
||||
// "input": "<path>", "companion": "<path>|null" }
|
||||
// Result: { "ok": true, "kind": ..., "bytes": <n>, "sha256": ...,
|
||||
// "suspect": ..., "issues": [...], "remapped": ... }
|
||||
// or { "ok": false, "error": "..." }
|
||||
// Result: { "ok": true, ... } with the fields of the job's kind (see `runJob`),
|
||||
// or { "ok": false, "error": "...", "profile": {...} }
|
||||
//
|
||||
// The wasm package directory is argv[2] (wasm-pack --target nodejs output).
|
||||
//
|
||||
// The driver calls the binding the way `web/worker.js` does: the input is
|
||||
// appended to an `InputBuffer` in slices, the recovered bytes are read through
|
||||
// the views the outcome hands out, and the digests the binding computes are
|
||||
// checked against digests of those bytes.
|
||||
//
|
||||
// Isolation: every job runs in a *fresh Node Worker thread* and that worker is
|
||||
// terminated before the next job starts. This matches the browser binding's
|
||||
// disposable-worker architecture: WebAssembly cannot recover from a trap in the
|
||||
@@ -21,7 +25,7 @@
|
||||
// hung call; on expiry the worker is terminated and the job reports an error.
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { closeSync, fstatSync, openSync, readFileSync, readSync } from "node:fs";
|
||||
import { createInterface } from "node:readline";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -32,55 +36,112 @@ function sha256(bytes) {
|
||||
return createHash("sha256").update(bytes).digest("hex");
|
||||
}
|
||||
|
||||
const SLICE = 8 * 1024 * 1024;
|
||||
|
||||
// Fill an `InputBuffer` from a file in slices, as the page does from a Blob.
|
||||
function load(wasm, file) {
|
||||
const fd = openSync(file, "r");
|
||||
try {
|
||||
const size = fstatSync(fd).size;
|
||||
const buffer = new wasm.InputBuffer(size);
|
||||
const slice = Buffer.allocUnsafe(Math.min(SLICE, Math.max(size, 1)));
|
||||
for (;;) {
|
||||
const read = readSync(fd, slice, 0, slice.length, null);
|
||||
if (read === 0) break;
|
||||
buffer.append(slice.subarray(0, read));
|
||||
}
|
||||
if (buffer.length !== size) throw new Error("short read");
|
||||
return buffer;
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
// The digest of a view, which must agree with the digest the binding reports.
|
||||
// The view is hashed first: it is valid only until the next call into the
|
||||
// module, and `report` is such a call.
|
||||
function digestOf(view, report) {
|
||||
if (!view || view.length === 0) return null;
|
||||
const digest = sha256(view);
|
||||
const reported = report();
|
||||
if (reported !== digest) throw new Error(`binding digest ${reported} is not the bytes' ${digest}`);
|
||||
return digest;
|
||||
}
|
||||
|
||||
// Runs in a worker: one job, one freshly instantiated module.
|
||||
function runJob(pkgDir, job) {
|
||||
const require = createRequire(import.meta.url);
|
||||
const wasm = require(path.join(pkgDir, "senbei_wasm.js"));
|
||||
let handle;
|
||||
if (job.op === "detect") {
|
||||
return { ok: true, kind: wasm.detect(readFileSync(job.input)) ?? null };
|
||||
}
|
||||
|
||||
const input = load(wasm, job.input);
|
||||
let outcome;
|
||||
try {
|
||||
if (job.op === "detect") {
|
||||
const bytes = readFileSync(job.input);
|
||||
return { ok: true, kind: wasm.detect(bytes) ?? null };
|
||||
}
|
||||
if (job.op === "unpack" || job.op === "unpack_force_exe") {
|
||||
const input = readFileSync(job.input);
|
||||
const companion = job.companion ? readFileSync(job.companion) : undefined;
|
||||
handle =
|
||||
job.op === "unpack"
|
||||
? wasm.unpack_file(input, companion)
|
||||
: wasm.unpack_file_force_exe(input, companion);
|
||||
const bytes = handle.bytes;
|
||||
return {
|
||||
ok: true,
|
||||
kind: handle.kind,
|
||||
bytes: bytes.length,
|
||||
sha256: sha256(bytes),
|
||||
suspect: handle.suspect,
|
||||
issues: handle.issues,
|
||||
companion: handle.companion,
|
||||
};
|
||||
// `unpack_pe` takes the companion buffer over.
|
||||
const companion = job.companion ? load(wasm, job.companion) : undefined;
|
||||
outcome = wasm.unpack_pe(input, companion, job.op === "unpack_force_exe", "en", undefined);
|
||||
} else if (job.op === "metadata") {
|
||||
outcome = wasm.restore_metadata(input, undefined, 0, "en");
|
||||
} else if (job.op === "library") {
|
||||
outcome = wasm.restore_library(input, "en", undefined);
|
||||
} else {
|
||||
return { ok: false, error: `unknown op ${job.op}` };
|
||||
}
|
||||
const info = JSON.parse(outcome.info);
|
||||
const profile = info.profile;
|
||||
if (info.status === "failed") return { ok: false, error: info.error?.text ?? null, profile };
|
||||
|
||||
// Each view is used before the next call into the module.
|
||||
const image = outcome.image();
|
||||
const bytes = image.length;
|
||||
const digest = digestOf(image, () => outcome.image_sha256());
|
||||
if (job.op === "metadata") {
|
||||
const data = readFileSync(job.input);
|
||||
handle = wasm.deobfuscate_metadata(data);
|
||||
const bytes = handle.bytes;
|
||||
return {
|
||||
ok: true,
|
||||
bytes: bytes.length,
|
||||
sha256: sha256(bytes),
|
||||
version: handle.version,
|
||||
methods: handle.methods,
|
||||
remapped: handle.remapped,
|
||||
modules: handle.modules,
|
||||
status: info.status,
|
||||
bytes,
|
||||
sha256: digest,
|
||||
version: info.metadata?.version ?? null,
|
||||
methods: info.metadata?.methods ?? null,
|
||||
remapped: info.metadata?.remapped ?? null,
|
||||
modules: info.metadata?.modules ?? null,
|
||||
layout: info.metadata?.layout ?? null,
|
||||
profile,
|
||||
};
|
||||
}
|
||||
return { ok: false, error: `unknown op ${job.op}` };
|
||||
if (job.op === "library") {
|
||||
const embedded = digestOf(outcome.embedded_metadata(), () => outcome.embedded_metadata_sha256());
|
||||
const module = outcome.take_module();
|
||||
return {
|
||||
ok: true,
|
||||
status: info.status,
|
||||
bytes,
|
||||
sha256: digest,
|
||||
embedded,
|
||||
module: module ? sha256(module) : null,
|
||||
elf: info.elf,
|
||||
profile,
|
||||
};
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
kind: info.kind,
|
||||
bytes,
|
||||
sha256: digest,
|
||||
suspect: info.suspect,
|
||||
issues: info.findings.map((finding) => finding.message),
|
||||
companion: info.companion,
|
||||
profile,
|
||||
};
|
||||
} finally {
|
||||
// The worker is terminated immediately after this, so this is belt and
|
||||
// braces: release the Rust-side allocation without waiting for GC.
|
||||
if (handle && typeof handle.free === "function") {
|
||||
// braces: release the Rust-side allocations without waiting for GC.
|
||||
for (const handle of [outcome, input]) {
|
||||
try {
|
||||
handle.free();
|
||||
handle?.free();
|
||||
} catch {
|
||||
// A poisoned instance after a trap can refuse; the worker dies anyway.
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<String, Range<usize>>),
|
||||
}
|
||||
|
||||
/// 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<StreamReport>,
|
||||
artifacts: Vec<ArtifactReport>,
|
||||
registry: BTreeMap<u32, LoadedModule>,
|
||||
@@ -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<u32, Vec<u8>>,
|
||||
direct: BTreeMap<String, Range<usize>>,
|
||||
}
|
||||
|
||||
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<MemoryExtraction> {
|
||||
let (stage1, extractor) = run_extraction(
|
||||
input,
|
||||
Path::new("<input>"),
|
||||
DEFAULT_OUTER_SIZE,
|
||||
DEFAULT_CIPHER_CONSTANT,
|
||||
limits,
|
||||
Sink::Memory(BTreeMap::new()),
|
||||
|_| Ok(()),
|
||||
)?;
|
||||
let (report, extractor) =
|
||||
extractor.into_report(stage1, "<input>".to_owned(), "<memory>".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::<Vec<_>>();
|
||||
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<StreamParent>,
|
||||
/// Reported for the bootstrap stream only.
|
||||
source_file_offset: Option<usize>,
|
||||
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::<Vec<_>>();
|
||||
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<StreamParent>,
|
||||
source_file_offset: Option<usize>,
|
||||
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<ArtifactReport> {
|
||||
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> {
|
||||
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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
@@ -117,3 +117,82 @@ pub(crate) fn load_artifacts(index_path: &Path) -> Result<BTreeMap<u32, Artifact
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// One stage-2 image resolved from an in-memory extraction.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct MemoryArtifact<'a> {
|
||||
pub data: &'a [u8],
|
||||
pub entry_offset: Option<u32>,
|
||||
}
|
||||
|
||||
/// [`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<BTreeMap<u32, MemoryArtifact<'a>>> {
|
||||
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::<Vec<_>>();
|
||||
if !missing.is_empty() {
|
||||
return invalid(format!(
|
||||
"module index lacks required IDs: {}",
|
||||
missing.join(", ")
|
||||
));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
+281
-123
@@ -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<Self> {
|
||||
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<Dialog>) -> Option<Self> {
|
||||
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::<Dialog>(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::<Dialog>(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<Dialog>) -> Option<VisibleDialog> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<PathBuf> = 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);
|
||||
|
||||
@@ -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<u8>,
|
||||
/// The unwrapped metadata blob, when the restored image embeds one.
|
||||
pub embedded_metadata: Option<Vec<u8>>,
|
||||
/// 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<Vec<u8>>,
|
||||
/// 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<LibraryBytes> {
|
||||
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<u8>,
|
||||
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<u32> {
|
||||
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<u8> {
|
||||
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#"<manifest package="com.example.app" android:versionCode="7">"#;
|
||||
assert_eq!(
|
||||
manifest_identity(manifest, false),
|
||||
Some(("com.example.app".to_owned(), "7".to_owned()))
|
||||
);
|
||||
assert_eq!(manifest_identity(manifest, true), None);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
|
||||
+2
-31
@@ -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<senbei_metadata::MetadataIdentity>,
|
||||
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
|
||||
|
||||
@@ -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<senbei_metadata::MetadataIdentity>,
|
||||
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<senbei_metadata::MetadataIdentity>,
|
||||
|
||||
Generated
+2
@@ -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",
|
||||
|
||||
@@ -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
|
||||
+514
-542
File diff suppressed because it is too large.
Load diff
+33
-8
@@ -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 `<name>.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 <dist>` copies the files the site needs, and only those, into `<dist>`.
|
||||
|
||||
## 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. |
|
||||
+925
-685
File diff suppressed because it is too large.
Load diff
Binary file not shown.
@@ -0,0 +1,94 @@
|
||||
Copyright (c) 2011 by Mariela Monsalve ([email protected]),
|
||||
with Reserved Font Name "Asul". All Rights Reserved.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 14 14"><path d="M3 7 7 11 11 3" fill="none" stroke="#e4e7ec"/></svg>
|
||||
|
After Width: | Height: | Size: 122 B |
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.2 KiB |
+852
@@ -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 ? '' : `<span class="badge">${badge[key]}</span>`;
|
||||
return (
|
||||
`<button class="tab${shown === key ? ' on' : ''}" data-act="tab" data-tab="${key}" role="tab" aria-selected="${shown === key}">` +
|
||||
`${esc(t(TAB_LABEL[key]))}${count}</button>`
|
||||
);
|
||||
};
|
||||
const actions = exports
|
||||
? `<span class="dacts"><button class="ghost" data-act="export">${esc(t('detail.export_json'))}</button>` +
|
||||
`<button class="ghost" data-act="export-text">${esc(t('detail.export_text'))}</button></span>`
|
||||
: '';
|
||||
return (
|
||||
`<div class="dhead${tabs.length ? '' : ' notabs'}"><div class="dtitle">` +
|
||||
`<button class="back" data-act="back" aria-label="${esc(t('inputs.title'))}">←</button>` +
|
||||
`<h2 title="${esc(title)}">${esc(title)}</h2>${tagText ? tag(tagText) : ''}${pills}` +
|
||||
`<span class="spacer"></span>${actions}</div>` +
|
||||
`${path ? `<div class="dpath mono" title="${esc(path)}">${esc(path)}</div>` : ''}` +
|
||||
`${tabs.length ? `<div class="tabs" role="tablist">${tabs.map(tab).join('')}</div>` : ''}</div>`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 ? `<div class="dbody scroll"><div class="pad">${html}</div></div>` : `<div class="dbody flush">${html}</div>`;
|
||||
|
||||
/**
|
||||
* 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 ? '<col>' : `<col style="width:${outer(width, index)}px">`,
|
||||
);
|
||||
const heads = columns.map(
|
||||
([label, , kind]) => `<th${kind === 'num' ? ' class="num"' : ''}>${esc(label)}</th>`,
|
||||
);
|
||||
return (
|
||||
`<div class="tbl-wrap"><table class="t grow-${grow + 1}${tall ? ' tall' : ''}" style="min-width:${fixed + 120}px">` +
|
||||
`<colgroup>${cols.join('')}</colgroup><thead><tr>${heads.join('')}</tr></thead>` +
|
||||
`<tbody>${rows.join('')}</tbody></table></div>`
|
||||
);
|
||||
}
|
||||
|
||||
const toned = (value, tone) => `<span class="c-${tone}">${esc(value)}</span>`;
|
||||
|
||||
/** 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) =>
|
||||
`<div class="logline${line.level === 'detail' ? ' detail' : ''}"><span class="ts">${localClock(line.at)}</span>` +
|
||||
`<span class="lv ${LEVEL_TONE[line.level] ?? ''}">${esc(levelLabel(line))}</span>` +
|
||||
`<span class="tx">${esc(lineText(line))}</span></div>`,
|
||||
);
|
||||
return `<div class="log${scrolls ? ' scroll' : ''}">${rows.join('')}</div>`;
|
||||
}
|
||||
|
||||
/** The log tab: a filter bar and the lines below it. */
|
||||
function logTab(lines) {
|
||||
const levels = LOG_LEVELS.map(
|
||||
([key, label]) =>
|
||||
`<button class="${state.logLevel === key ? 'on' : ''}" data-act="loglevel" data-level="${key}" aria-pressed="${state.logLevel === key}">${esc(t(label))}</button>`,
|
||||
);
|
||||
return (
|
||||
`<div class="logbar"><div class="seg">${levels.join('')}</div><span class="spacer"></span>` +
|
||||
`<button class="ghost" data-act="copy-log">${esc(t('log.copy'))}</button></div>${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 = '<span class="arrow">→</span>';
|
||||
|
||||
function stageChip({ icon = '', tone = 'skip', name, duration = '', status = '', detail = '', dimmed = false }) {
|
||||
return (
|
||||
`<div class="stage${dimmed ? ' dimmed' : ''}"><div class="sname">` +
|
||||
`${icon ? `<span class="c-${tone}${icon === '✓' ? ' sicon' : ''}">${icon}</span>` : ''}<span>${esc(name)}</span>` +
|
||||
`${duration ? `<span class="sdur">${esc(duration)}</span>` : ''}</div>` +
|
||||
`${status ? `<div class="sstat c-${tone}">${esc(status)}</div>` : ''}` +
|
||||
`${detail ? `<div class="sdet">${esc(detail)}</div>` : ''}</div>`
|
||||
);
|
||||
}
|
||||
|
||||
/** 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'), `<div class="stages">${chips.join(ARROW)}</div>`, { 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'), `<div class="stages">${chips.join(ARROW)}</div>`, { 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 (
|
||||
`<tr data-act="select" data-id="${item.id}" tabindex="0"><td class="c-dot">${dot(row.dot)}</td>` +
|
||||
`<td>${esc(item.name)}</td><td>${tag(typeTag(item))}</td>` +
|
||||
`<td class="${row.tone ? `c-${row.tone}` : 'faint'}">${esc(row.label)}</td>` +
|
||||
`<td>${esc(route)}</td><td class="num">${esc(row.time ?? '')}</td></tr>`
|
||||
);
|
||||
});
|
||||
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) => `<div class="stack">${lines.filter(Boolean).map((line) => `<div>${line}</div>`).join('')}</div>`;
|
||||
|
||||
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'), `<span>${esc(state)}</span><span>·</span>${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'),
|
||||
`<div class="action"><button class="primary" data-act="run-item" data-id="${item.id}"${blocked ? ' disabled' : ''}>${esc(t('tb.unpack'))}</button>` +
|
||||
`<span class="dim">${esc(t('web.unpack_desc'))}</span></div>` +
|
||||
(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
|
||||
? `<span class="flags">${evidence.map((name) => pill('skip', tv('evidence', name))).join('')}</span>`
|
||||
: 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 (
|
||||
`<div class="route"><div class="rhead"><span>${esc(tv('layout', route.layout))}</span>` +
|
||||
`${selected ? `<span class="star">★ ${esc(t('ov.selected'))}</span>` : ''}<span class="spacer"></span>` +
|
||||
`${pill(OUTCOME_TONE[route.outcome] ?? 'err', tv('outcome', route.outcome))}</div>` +
|
||||
`${reasons.length ? messages(reasons, item.result.lang) : ''}</div>`
|
||||
);
|
||||
});
|
||||
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 = `<span class="c-ok">${esc(t('web.saved', { path: shownPath(output.saved) }))}</span>`;
|
||||
} else if (output.refused) {
|
||||
kept = `<span class="c-warn">${esc(t('web.save_refused', { name: baseName(output.path) }))}</span>`;
|
||||
} else if (output.saveFailed) {
|
||||
kept = `<span class="c-err">${esc(t('web.save_failed', { path: shownPath(output.saveFailed) }))}</span>`;
|
||||
}
|
||||
return stack([
|
||||
`${mono(shownPath(output.path))}${output.embedded ? ` ${tag(t('web.embedded_metadata'))}` : ''}`,
|
||||
`<span class="orow"><span>${esc(formatBytes(output.size))}</span>` +
|
||||
`<button class="ghost" data-act="download" data-id="${item.id}" data-n="${index}">${esc(t('web.download'))}</button></span>`,
|
||||
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 = `<span class="mono faint">${esc(`${baseName(item.relPath)}._`)}</span>`;
|
||||
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 =
|
||||
`<td class="c-dot">${dot(tone)}</td>` +
|
||||
`<td class="two"><div class="mono">${esc(entry.name)}</div><div class="place">${esc(entryPlace(item, entry))}</div></td>` +
|
||||
`<td>${tag(typeTag(entry))}</td><td class="c-${tone}">${esc(t(key))}</td>`;
|
||||
if (routes) {
|
||||
cells +=
|
||||
`<td class="two"><div>${esc(routeOf(entry) ?? '')}</div>` +
|
||||
`${remapped == null ? '' : `<div class="place">${esc(t('EntriesRemapped', { n: formatCount(remapped) }))}</div>`}</td>`;
|
||||
}
|
||||
if (outputs) cells += `<td class="mono">${esc(shownPath(entry.result?.outputs?.[0]?.path ?? ''))}</td>`;
|
||||
return `<tr data-act="select" data-id="${entry.id}" tabindex="0">${cells}</tr>`;
|
||||
});
|
||||
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) =>
|
||||
`<tr><td class="mono">${esc(archive.label ? baseName(archive.label) : item.name)}</td>` +
|
||||
`<td>${archive.identity ? mono(archive.identity[0]) : faint(t('pkg.unnamed'))}</td>` +
|
||||
`<td class="mono">${esc(archive.identity?.[1] ?? '')}</td></tr>`,
|
||||
);
|
||||
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 (
|
||||
`<label class="check"><input type="checkbox" data-change="non-targets"${state.showNonTargets ? ' checked' : ''}>` +
|
||||
`<span class="dim">${esc(t('EntriesShowNonTargets', { n: others }))}</span></label>` +
|
||||
entryTable(item, shown) +
|
||||
fold(
|
||||
'inv',
|
||||
`inv:${item.id}`,
|
||||
esc(t('PkgInventory', { n: names.length })),
|
||||
`<pre class="well mono">${esc(names.map(shownPath).join('\n'))}</pre>`,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
`<div class="empty"><div class="drop"><img src="assets/icon-128.png" width="84" height="84" alt="">` +
|
||||
`<h2>${esc(t('empty.title'))}</h2>` +
|
||||
`<div class="kinds">${kinds.map((kind) => `<span class="tag mono">${esc(kind)}</span>`).join('')}</div>` +
|
||||
`<div class="acts"><button class="primary" data-act="add-files">${esc(t('tb.add_files'))}</button>` +
|
||||
`<button data-act="add-folder">${esc(t('tb.add_folder'))}</button></div>` +
|
||||
`<p class="faint">${esc(t('empty.local'))}</p></div></div>`
|
||||
);
|
||||
}
|
||||
|
||||
const pick = () => `<div class="pick faint">${esc(t('detail.pick'))}</div>`;
|
||||
|
||||
/** 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);
|
||||
}
|
||||
+196
@@ -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;
|
||||
}
|
||||
}
|
||||
+60
@@ -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;
|
||||
}
|
||||
+268
@@ -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. <strong>Only process binaries you own or are explicitly authorized to analyze.</strong>",
|
||||
"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 <strong>your</strong> 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.",
|
||||
};
|
||||
+268
@@ -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は、すでに正当に所有しているソフトウェアの合法的なリバースエンジニアリング、セキュリティ研究、および保全のための研究・相互運用性ツールです。<strong>ご自身が所有するバイナリ、または解析の明示的な許可を得ているバイナリのみを処理してください。</strong>",
|
||||
"legal.p2": "技術的保護手段の回避は、お住まいの法域で制限されている場合があります (たとえば米国のDMCA §1201。同条にはセキュリティ研究および相互運用性のための例外規定があります)。ご利用が合法であることを確認するのは<strong>ご自身の</strong>責任です。",
|
||||
"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": "この入力を読み込めませんでした。",
|
||||
};
|
||||
+268
@@ -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는 이미 적법하게 보유한 소프트웨어의 합법적인 리버스 엔지니어링, 보안 연구 및 보존을 위한 연구 및 상호운용성 도구입니다. <strong>본인이 소유하거나 분석할 명시적 권한이 있는 바이너리만 처리하십시오.</strong>",
|
||||
"legal.p2": "기술적 보호 조치를 우회하는 행위는 관할권에 따라 제한될 수 있습니다(예: 보안 연구 및 상호운용성에 대한 예외 조항을 포함하는 미국 DMCA §1201). 사용의 적법성을 보장하는 것은 <strong>사용자 본인</strong>의 책임입니다.",
|
||||
"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": "이 입력을 읽을 수 없습니다.",
|
||||
};
|
||||
@@ -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": "이 입력을 읽을 수 없습니다."
|
||||
}
|
||||
}
|
||||
@@ -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 是一款用于研究与互操作性的工具,用于对你已合法拥有的软件进行合法的逆向工程、安全研究与保存。<strong>请仅处理你拥有或已获明确授权分析的二进制文件。</strong>",
|
||||
"legal.p2": "规避技术保护措施在你所在的司法管辖区可能受到限制(例如美国 DMCA §1201 的规定,其中包含针对安全研究与互操作性的豁免条款)。确保使用行为合法是<strong>你本人</strong>的责任。",
|
||||
"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": "无法读取该输入项。",
|
||||
};
|
||||
@@ -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 是研究與互通性工具,用於對您已合法持有的軟體進行合法逆向工程、安全研究與保存。<strong>請僅處理您擁有或已獲明確授權分析的二進位檔。</strong>",
|
||||
"legal.p2": "規避科技保護措施在您所在的司法管轄區可能受到限制(例如美國 DMCA §1201,其中包含針對安全研究與互通性的豁免條款)。確保您的使用行為合法是<strong>您本人</strong>的責任。",
|
||||
"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": "無法讀取此輸入項。",
|
||||
};
|
||||
+33
-75
@@ -3,86 +3,44 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Senbei — static CrackProof unpacker</title>
|
||||
<meta name="color-scheme" content="dark">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self'; font-src 'self'; connect-src 'self'; worker-src 'self'; base-uri 'none'; form-action 'none'">
|
||||
<meta name="description" content="Senbei: a static unpacker for CrackProof-protected Windows PE files, Android AArch64 libraries, and il2cpp metadata. Runs in this browser; files are never uploaded.">
|
||||
<title>Senbei</title>
|
||||
<link rel="icon" href="assets/icon-32.png">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<link rel="modulepreload" href="i18n.js">
|
||||
<link rel="modulepreload" href="state.js">
|
||||
<link rel="modulepreload" href="view.js">
|
||||
<link rel="modulepreload" href="detail.js">
|
||||
<link rel="modulepreload" href="ui.js">
|
||||
<link rel="modulepreload" href="model.js">
|
||||
<link rel="modulepreload" href="engine.js">
|
||||
<link rel="modulepreload" href="scan.js">
|
||||
<link rel="modulepreload" href="run.js">
|
||||
<link rel="modulepreload" href="report.js">
|
||||
<script type="module" src="app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="legal-overlay" role="dialog" aria-modal="true" aria-labelledby="legal-title">
|
||||
<div class="legal-box">
|
||||
<h2 id="legal-title">Legal notice — read before use</h2>
|
||||
<p>
|
||||
Senbei is a research and interoperability tool for lawful reverse
|
||||
engineering, security research, and preservation of software you already
|
||||
legitimately possess. <strong>Only process binaries you own or are
|
||||
explicitly authorized to analyze.</strong>
|
||||
</p>
|
||||
<p>
|
||||
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 <strong>your</strong> responsibility.
|
||||
</p>
|
||||
<p>
|
||||
Senbei performs a purely static transformation of files on your device:
|
||||
it bypasses no access control by itself, ships no keys and no vendor
|
||||
code, and uploads nothing — everything runs locally in your browser.
|
||||
Do not redistribute decrypted outputs. 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.
|
||||
</p>
|
||||
<button id="legal-accept" type="button">I understand and accept</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<main>
|
||||
<header class="topbar">
|
||||
<h1>Senbei <span class="tag">web</span></h1>
|
||||
<a class="github-link" href="https://github.com/Momoko-Ayase/Senbei" target="_blank" rel="noopener"
|
||||
title="Senbei on GitHub" aria-label="Senbei on GitHub">
|
||||
<svg viewBox="0 0 16 16" width="22" height="22" aria-hidden="true">
|
||||
<path fill="currentColor" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8Z"/>
|
||||
</svg>
|
||||
</a>
|
||||
<div id="app">
|
||||
<header class="topbar" id="topbar">
|
||||
<div class="brand"><img src="assets/icon-32.png" width="26" height="26" alt=""><span class="word">Senbei</span></div>
|
||||
</header>
|
||||
<p class="lede">
|
||||
Static unpacker for CrackProof-protected PE files, running entirely in
|
||||
your browser. <strong>No file ever leaves your device.</strong>
|
||||
</p>
|
||||
|
||||
<div id="dropzone" tabindex="0" role="button"
|
||||
aria-label="Drop protected files here or press Enter to browse">
|
||||
<p><strong>Drop files here</strong> or click to browse</p>
|
||||
<p class="hint">
|
||||
Protected <code>.exe</code> / <code>.dll</code> modules, optional
|
||||
<code>._</code> companions, or an il2cpp
|
||||
<code>global-metadata.dat</code>. Android packages
|
||||
(<code>.apk</code> / <code>.apks</code> / <code>.xapk</code>) and
|
||||
<code>.so</code> libraries are recognized but need the CLI.
|
||||
</p>
|
||||
<input type="file" id="picker" multiple hidden>
|
||||
<div class="main blank" id="main">
|
||||
<aside class="inputs" id="inputs"></aside>
|
||||
<section class="detail" id="detail"></section>
|
||||
</div>
|
||||
|
||||
<div class="limits">
|
||||
<label for="limit-mib">Input limit per module (MiB)</label>
|
||||
<input id="limit-mib" type="number" min="8" max="4096" step="8" value="256"
|
||||
inputmode="numeric" aria-describedby="limit-hint">
|
||||
<p id="limit-hint" class="hint"></p>
|
||||
</div>
|
||||
|
||||
<ul id="files"></ul>
|
||||
|
||||
<div class="actions" id="actions" hidden>
|
||||
<button id="unpack-btn" type="button">Unpack</button>
|
||||
<button id="export-btn" type="button" class="secondary">Export JSON</button>
|
||||
<button id="clear-btn" type="button" class="secondary">Clear</button>
|
||||
</div>
|
||||
|
||||
<footer>
|
||||
<p><a href="#" id="legal-link">Legal notice</a> ·
|
||||
Senbei is free software under the AGPL-3.0 license.</p>
|
||||
<footer class="statusbar">
|
||||
<div class="status-line" id="status"></div>
|
||||
<button class="cancel" id="cancel" data-act="cancel" hidden></button>
|
||||
</footer>
|
||||
</main>
|
||||
<script type="module" src="app.js"></script>
|
||||
</div>
|
||||
<div id="menu"></div>
|
||||
<div class="dragover" id="dragover" hidden><div class="box"><h2 id="dragover-title"></h2></div></div>
|
||||
<dialog class="modal" id="legal"></dialog>
|
||||
<dialog class="modal" id="settings"></dialog>
|
||||
<input type="file" id="pick-files" multiple hidden>
|
||||
<input type="file" id="pick-folder" webkitdirectory hidden>
|
||||
<noscript><p style="padding:16px">Senbei runs in the browser and needs JavaScript.</p></noscript>
|
||||
</body>
|
||||
</html>
|
||||
+311
@@ -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: `<name>.exe._` or `<name>.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.
|
||||
*
|
||||
* `<root>/lib/<abi>/<name>.so` and `<root>/assets/**\/global-metadata.dat`
|
||||
* share `<root>`. 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;
|
||||
}
|
||||
}
|
||||
+149
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -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 `<manifest>` 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);
|
||||
}
|
||||
+265
-377
@@ -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 `<module>._` 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}`;
|
||||
}
|
||||
+494
@@ -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();
|
||||
}
|
||||
+89
@@ -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 };
|
||||
}
|
||||
+251
@@ -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]}`;
|
||||
}
|
||||
+486
-435
@@ -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); }
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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('>▶</span> 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('>▶</span> 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}</p>`));
|
||||
}
|
||||
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 = '<img src=x onerror=alert(1)>"\'&';
|
||||
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('<img src=x');
|
||||
assert.equal(at, -1, html.slice(Math.max(0, at - 200), at + 80));
|
||||
assert.ok(!/onerror=alert\(1\)>"/.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();
|
||||
});
|
||||
+306
-480
@@ -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);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
+96
@@ -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`;
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
// Generate the page's language catalogs.
|
||||
//
|
||||
// node web/tools/gen-i18n.mjs write web/i18n/<lang>.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/<lang>.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();
|
||||
@@ -0,0 +1,46 @@
|
||||
// Stage the static site: the files the page loads, and nothing else.
|
||||
//
|
||||
// node web/tools/stage.mjs <dist>
|
||||
//
|
||||
// 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 <dist>');
|
||||
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();
|
||||
@@ -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) => `<span class="pill ${tone}">${esc(text)}</span>`;
|
||||
export const tag = (text) => `<span class="tag">${esc(text)}</span>`;
|
||||
export const note = (text) => `<p class="note">${esc(text)}</p>`;
|
||||
export const dim = (text) => `<span class="dim">${esc(text)}</span>`;
|
||||
export const faint = (text) => `<span class="faint">${esc(text)}</span>`;
|
||||
export const mono = (text) => `<span class="mono">${esc(text)}</span>`;
|
||||
|
||||
/** A status dot; no tone draws a hollow one. */
|
||||
export const dot = (tone) => `<span class="dot ${tone ? `bg-${tone}` : 'hollow'}"></span>`;
|
||||
|
||||
/**
|
||||
* 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) => `<span class="room" aria-hidden="true">${esc(label)}</span>`).join('');
|
||||
const cells = rows
|
||||
.filter(Boolean)
|
||||
.map(([key, value], index) => `<div class="k">${esc(key)}${index === 0 ? room : ''}</div><div class="v">${value}</div>`);
|
||||
return `<div class="kv">${cells.join('')}</div>`;
|
||||
}
|
||||
|
||||
/** 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 ? `<span class="aside">${options.aside}</span>` : '';
|
||||
const head = title === null ? '' : `<h3>${esc(title)}${aside}</h3>`;
|
||||
return `<section class="card${options.wide ? ' wide' : ''}">${head}${body}</section>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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('<section class="card wide"');
|
||||
const out = cards.filter(Boolean);
|
||||
let run = 0;
|
||||
for (let index = 0; index <= out.length; index += 1) {
|
||||
if (index < out.length && !wide(out[index])) {
|
||||
run += 1;
|
||||
continue;
|
||||
}
|
||||
if (run % 2 === 1) out[index - 1] = out[index - 1].replace('class="card"', 'class="card wide"');
|
||||
run = 0;
|
||||
}
|
||||
return out.length ? `<div class="cards">${out.join('')}</div>` : '';
|
||||
}
|
||||
|
||||
/** 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 ? `<code>${esc(part)}</code>` : 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) =>
|
||||
`<details class="fold ${kind}" data-fold="${esc(key)}"${state.unfolded.has(key) ? ' open' : ''}>` +
|
||||
`<summary>${summary}</summary>${body}</details>`;
|
||||
|
||||
/**
|
||||
* 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')), `<pre class="mono">${esc(more)}</pre>`)
|
||||
: '';
|
||||
return (
|
||||
`<div class="msg ${kind}"><span class="c-${kind}">${MESSAGE_ICON[kind] ?? 'i'}</span>` +
|
||||
`<div><div>${codeSpans(show(message, lang))}</div>${detail}</div></div>`
|
||||
);
|
||||
});
|
||||
return `<div class="msgs">${rows.join('')}</div>`;
|
||||
}
|
||||
|
||||
/** A hash, shortened, with the whole of it as the tooltip and a copy button. */
|
||||
export function hash(sha256) {
|
||||
if (!sha256) return '';
|
||||
return (
|
||||
`<span class="hash"><span class="mono" title="${esc(sha256)}">${esc(shortHash(sha256))}</span>` +
|
||||
`<button class="ghost copy" data-act="copy" data-text="${esc(sha256)}">${esc(t('detail.copy'))}</button></span>`
|
||||
);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
+326
@@ -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) =>
|
||||
`<span class="caret" data-act="toggle" data-id="${id}">${open ? '▼' : '▶'}</span>`;
|
||||
|
||||
function rowHtml(item, withCaret) {
|
||||
const row = rowState(item);
|
||||
const selected = isSelected(item.id);
|
||||
const open = !state.collapsed.has(item.id);
|
||||
const label = `<span class="st${row.tone ? ` c-${row.tone}` : ''}">${esc(row.label)}</span>`;
|
||||
const extra = row.extra ? `<span>·</span><span class="ex">${esc(row.extra)}</span>` : '';
|
||||
const time = row.time ? `<span class="time">${esc(row.time)}</span>` : '';
|
||||
return (
|
||||
`<div class="row${item.isEntry ? ' nested' : ''}${selected ? ' selected' : ''}" ${selectable(item.id, selected)} title="${esc(shownPath(fullPath(item)))}">` +
|
||||
`${withCaret ? caret(item.id, open) : ''}${dot(row.dot)}` +
|
||||
`<span class="name">${esc(item.name)}</span>${tag(typeTag(item))}` +
|
||||
`<span class="meta">${label}${extra}<span class="spacer"></span>${time}</span></div>`
|
||||
);
|
||||
}
|
||||
|
||||
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:
|
||||
`<div class="row others" data-act="show-entries" data-id="${item.id}" tabindex="0" role="button">` +
|
||||
`${esc(t('EntriesOthers', { n: others }))}</div>`,
|
||||
});
|
||||
}
|
||||
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 = `<span class="gsub c-info">${esc(t('GroupScanning', { n: group.found }))}</span>`;
|
||||
} else if (folder) {
|
||||
sub = `<span class="gsub">${esc(group.lastRun ? `${modeLabel()} · ${path}` : path)}</span>`;
|
||||
}
|
||||
return (
|
||||
`<div class="group-h${selected ? ' selected' : ''}" ${selectable(group.id, selected)}${path ? ` title="${esc(path)}"` : ''}>` +
|
||||
`${caret(group.id, !state.collapsed.has(group.id))}` +
|
||||
`<span class="gname">${esc(groupName(group))}</span>` +
|
||||
`<span class="gcount">${group.scanning ? group.found : shown}</span>${sub}</div>`
|
||||
);
|
||||
}
|
||||
|
||||
/** The parts of the inputs pane that stay put while its list changes. */
|
||||
export function inputsFrame() {
|
||||
const search = esc(t('inputs.search'));
|
||||
return (
|
||||
`<div class="inputs-head"><div class="title"><span>${esc(t('inputs.title'))}</span>` +
|
||||
`<button class="ghost" id="clear" data-act="clear">${esc(t('inputs.clear'))}</button></div>` +
|
||||
`<div class="chips" id="chips"></div>` +
|
||||
`<input type="search" class="search" id="search" placeholder="${search}" aria-label="${search}"></div>` +
|
||||
`<div class="list" id="list" role="listbox" aria-multiselectable="true" aria-label="${esc(t('inputs.title'))}"></div>`
|
||||
);
|
||||
}
|
||||
|
||||
/** 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 (
|
||||
`<button class="chip${on ? ' on' : ''}" data-act="filter" data-filter="${key}" aria-pressed="${on}">` +
|
||||
`${esc(t(`filter.${key}`))}<span class="n">${count[key]}</span></button>`
|
||||
);
|
||||
})
|
||||
.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: `<p class="faint">${esc(t('inputs.none'))}</p>` });
|
||||
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 (
|
||||
`<div class="brand"><img src="assets/icon-32.png" width="26" height="26" alt="">` +
|
||||
`<span class="word">Senbei</span><span class="ver">${VERSION}</span></div>` +
|
||||
`<button data-act="add-files" title="Ctrl+O">${esc(t('tb.add_files'))}</button>` +
|
||||
`<button data-act="add-folder">${esc(t('tb.add_folder'))}</button><span class="sep"></span>` +
|
||||
`<button class="primary" data-act="run" title="${esc(t('web.unpack_tip'))}"${idle ? '' : ' disabled'}><span class="ico">▶</span> ${esc(label)}</button>` +
|
||||
`<button data-act="download-all"${allOutputs().length ? '' : ' disabled'}>${esc(t('web.download_all'))}</button>` +
|
||||
`<span class="spacer"></span>` +
|
||||
`<button class="out-chip" data-act="out-menu" title="${esc(t('web.out_tip'))}" aria-haspopup="menu"${outputBusy() ? ' disabled' : ''}>` +
|
||||
`<span>${esc(t('tb.output'))}</span><b>${esc(outputLabel())}</b><span class="faint">▾</span></button>` +
|
||||
`<button class="gear" data-act="settings" title="${esc(t('tb.settings'))}" aria-label="${esc(t('tb.settings'))}">⚙</button>`
|
||||
);
|
||||
}
|
||||
|
||||
/** 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
|
||||
? `<span class="cur mono">${esc(run.current.name)}</span>` +
|
||||
`${run.step ? `<span class="step">${esc(stepText(run.step))}</span>` : ''}` +
|
||||
`<span class="clock faint">${formatClock(performance.now() - run.started)}</span>`
|
||||
: '';
|
||||
return (
|
||||
`<span class="c-info">●</span><b>${esc(t('tb.unpack'))}</b>` +
|
||||
`<div class="progress" role="progressbar" aria-label="${esc(t('run.progress'))}" aria-valuemin="0" aria-valuemax="${total}" aria-valuenow="${run.done}">` +
|
||||
`<div style="width:${percent}%"></div></div><span>${run.done} / ${total}</span>${current}` +
|
||||
`<span class="spacer"></span>` +
|
||||
`${run.stopping ? `<span class="c-warn">${esc(t('run.stopping'))}</span>` : ''}`
|
||||
);
|
||||
}
|
||||
if (state.scans.length) {
|
||||
const group = state.scans[0].group;
|
||||
return `<span class="c-info">●</span><span>${esc(t('ScanStatus', { p: groupName(group), n: group.found }))}</span>`;
|
||||
}
|
||||
const notice = state.notice
|
||||
? `<span class="notice${state.notice.tone ? ` c-${state.notice.tone}` : ''}">${esc(show(state.notice))}</span>`
|
||||
: '';
|
||||
return `<span class="c-ok">●</span><span>${esc(t('status.ready'))}</span>${notice}`;
|
||||
}
|
||||
|
||||
// ---------- menus ----------
|
||||
|
||||
function choice(act, on, label, sub) {
|
||||
return (
|
||||
`<button class="ctx-item" data-act="${act}" role="menuitemradio" aria-checked="${on}">` +
|
||||
`<span class="radio">${on ? '●' : '○'}</span><span><span>${esc(label)}</span>` +
|
||||
`${sub ? `<span class="sub mono">${esc(sub)}</span>` : ''}</span></button>`
|
||||
);
|
||||
}
|
||||
|
||||
/** 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
|
||||
? `<button class="ctx-item" data-act="out-choose" role="menuitem" aria-describedby="out-folder-help"><span class="radio"></span><span>${esc(t('settings.output_choose'))}</span></button>` +
|
||||
`<p class="ctx-note" id="out-folder-help">${esc(t('web.out_folder_help'))}</p>`
|
||||
: `<p class="ctx-note">${esc(t('web.out_unsupported'))}</p>`;
|
||||
return `${choices}<div class="ctx-sep"></div>${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 = '') =>
|
||||
`<button class="ctx-item" data-act="${act}" data-id="${id}" role="menuitem"${disabled ? ' disabled' : ''}>` +
|
||||
`<span>${esc(label)}</span>${shortcut ? `<span class="kbd">${shortcut}</span>` : ''}</button>`;
|
||||
const sep = '<div class="ctx-sep"></div>';
|
||||
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]) => `<option value="${code}"${code === language() ? ' selected' : ''}>${name}</option>`,
|
||||
);
|
||||
return `<select id="${id}" data-change="language" aria-label="${esc(t('settings.language'))}">${options.join('')}</select>`;
|
||||
}
|
||||
|
||||
/** 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 <strong>.
|
||||
const text = ['legal.p1', 'legal.p2', 'legal.p3', 'legal.p4'].map((key) => `<p>${t(key)}</p>`);
|
||||
const close = accepted
|
||||
? `<button class="primary" data-act="close-legal">${esc(t('settings.done'))}</button>`
|
||||
: `<button class="primary" data-act="accept">${esc(t('legal.accept'))}</button>`;
|
||||
return (
|
||||
`<div class="modal-h"><img src="assets/icon-32.png" width="24" height="24" alt=""><h2>${esc(t('legal.title'))}</h2>` +
|
||||
`<span class="spacer"></span>${languageSelect('legal-language')}</div>` +
|
||||
`<div class="modal-b">${text.join('')}</div><div class="modal-f"><span class="spacer"></span>${close}</div>`
|
||||
);
|
||||
}
|
||||
|
||||
/** A settings row: its label, its control, and an optional help line. */
|
||||
function field(id, label, control, help) {
|
||||
const name = id ? `<label for="${id}">${esc(label)}</label>` : `<span class="flabel">${esc(label)}</span>`;
|
||||
const helpId = id ? ` id="${id}-help"` : '';
|
||||
return (
|
||||
`<div class="field">${name}<div><div class="control">${control}</div>` +
|
||||
`${help ? `<p class="help"${helpId}>${esc(help)}</p>` : ''}</div></div>`
|
||||
);
|
||||
}
|
||||
|
||||
function settingsPane(canPick) {
|
||||
if (state.settingsTab === 'memory') {
|
||||
const mib = Math.round(state.limitBytes / (1024 * 1024));
|
||||
return field(
|
||||
'set-limit',
|
||||
t('web.limit'),
|
||||
`<input type="number" id="set-limit" data-change="limit" min="${MIN_LIMIT_MIB}" max="${MAX_LIMIT_MIB}" step="1" value="${mib}"><span>MiB</span>`,
|
||||
t('web.limit_help'),
|
||||
);
|
||||
}
|
||||
if (state.settingsTab === 'about') {
|
||||
return (
|
||||
`<div class="about"><img src="assets/icon-128.png" width="72" height="72" alt=""><div><div class="word">Senbei</div>` +
|
||||
`<div class="dim">${esc(t('AboutVersion', { v: VERSION }))}</div></div></div><p class="dim">${esc(t('about.desc'))}</p>` +
|
||||
field(null, t('about.license'), '<a href="LICENSE" target="_blank" rel="noopener">AGPL-3.0-only</a>') +
|
||||
field(
|
||||
null,
|
||||
t('about.source'),
|
||||
'<a class="mono" href="https://github.com/Momoko-Ayase/Senbei" target="_blank" rel="noopener">github.com/Momoko-Ayase/Senbei</a>',
|
||||
) +
|
||||
`<div><button data-act="show-legal">${esc(t('about.legal'))}</button></div>`
|
||||
);
|
||||
}
|
||||
const option = (value, label, on) => `<option value="${value}"${on ? ' selected' : ''}>${esc(label)}</option>`;
|
||||
const folder = state.out.dir;
|
||||
const output =
|
||||
`<select id="set-output" data-change="output" aria-describedby="set-output-help"${outputBusy() ? ' disabled' : ''}>` +
|
||||
option('downloads', t('web.out_downloads'), state.out.mode === 'downloads') +
|
||||
(folder ? option('folder', shownPath(`${folder.name}/unpack`), state.out.mode === 'folder') : '') +
|
||||
(canPick ? option('choose', t('settings.output_choose'), false) : '') +
|
||||
`</select>`;
|
||||
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 `<button class="nav${on ? ' on' : ''}" data-act="settings-tab" data-tab="${key}" role="tab" aria-selected="${on}">${esc(t(`settings.tab_${key}`))}</button>`;
|
||||
});
|
||||
return (
|
||||
`<div class="modal-h"><h2>${esc(t('settings.title'))}</h2><span class="spacer"></span>` +
|
||||
`<button class="ghost" data-act="close-settings" aria-label="${esc(t('settings.done'))}">✕</button></div>` +
|
||||
`<div class="set-body"><nav class="set-nav" role="tablist">${nav.join('')}</nav>` +
|
||||
`<div class="set-pane" role="tabpanel">${settingsPane(canPick)}</div></div>` +
|
||||
`<div class="modal-f"><button class="ghost" data-act="reset"${outputBusy() ? ' disabled' : ''}>${esc(t('settings.reset'))}</button><span class="spacer"></span>` +
|
||||
`<button class="primary" data-act="close-settings">${esc(t('settings.done'))}</button></div>`
|
||||
);
|
||||
}
|
||||
+156
-79
@@ -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),
|
||||
});
|
||||
}
|
||||
};
|
||||
+388
@@ -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' });
|
||||
}
|
||||
Reference in new issue
Block a user