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

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

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

No files matched your search

+69
View File
@@ -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);
+208
View File
@@ -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);
});
+153
View File
@@ -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');
});
+473
View File
@@ -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('&lt;img src=x onerror=alert(1)&gt;&quot;&#39;&amp;'));
// The text report is plain text: the name is in it as it is.
assert.ok(reportText(group.items).includes(hostile));
reset();
});
+306 -480
View File
@@ -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);
});
+209
View File
@@ -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);
});
+137
View File
@@ -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');
});